summaryrefslogtreecommitdiff
path: root/phlox/login.go
blob: 27decf48908fbb5e237f7df5cc6152be663dc7ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main

import (
	"fmt"
	"net/http"
	db "sanine.net/git/phlox/db"
)


func LoginUser(username, password string) (bool, db.Session, error) {
	auth, user, err := p.AuthenticateUser(username, password)
	if err != nil {
		return false, db.Session{}, err
	}
	if auth == false {
		return false, db.Session{}, nil
	}
	// auth was successful!
	session, err := p.CreateSession(user)
	if err != nil {
		return false, db.Session{}, err
	}
	return true, session, nil
}


func LoginPostHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	username := r.Form.Get("username")
	password := r.Form.Get("password")
	redirect := r.Form.Get("redirect")

	auth, session, err := LoginUser(username, password)
	if err != nil {
		// respond with error page
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "an error was encountered when processing the request")
		log.Error(err)
	}

	if !auth {
		// not allowed!
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(w, "bad username or password")
		log.Errorf("failed login for %v", username)
	}

	http.SetCookie(w, &http.Cookie{
		Name: "phlox-session-id",
		Value: session.Id,
		SameSite: http.SameSiteLaxMode,
	}

	http.Header.Add("Location", redirect)
	http.WriteHeader(http.StatusTemporaryRedirect)
}