summaryrefslogtreecommitdiff
path: root/login.go
blob: d1265e54e2eb4675470b55a4330408d56bfda622 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main

import (
	"strings"
	"net/http"
	"sanine.net/git/phlox/page"
	"sanine.net/git/phlox/config"
	"sanine.net/git/phlox/auth"
	log "github.com/sirupsen/logrus"
)


func Login(
	w http.ResponseWriter,
	r *http.Request,
	users map[string]config.User,
	s *auth.Sessions,
	pages page.Pages,
) {
	if r.Method == "POST" {
		LoginPostHandler(w, r, users, s, pages)
	} else {
		LoginGetHandler(w, r, s, pages)
	}
}


func Logout(
	w http.ResponseWriter,
	r *http.Request,
	s *auth.Sessions,
) {
	if authenticateRequest(r, s) {
		cookie, _ := r.Cookie("phlox-session")
		s.DeleteSession(cookie.Value)
	}

	w.Header().Add("Location", "/phlox/login")
	w.WriteHeader(http.StatusTemporaryRedirect)
}


func LoginPostHandler(
	w http.ResponseWriter, 
	r *http.Request, 
	users map[string]config.User,
	s *auth.Sessions,
	pages page.Pages,
) {
	loggedIn := authenticateRequest(r, s)
	if loggedIn {
		pages.ServeLoggedIn(w)
		return
	}

	r.ParseForm()
	username := r.Form.Get("username")
	password := strings.TrimSpace(r.Form.Get("password"))

	user, ok := users[username]
	if !ok {
		w.WriteHeader(http.StatusUnauthorized)
		w.Write([]byte("bad username or password"))
	}

	ok = auth.AuthenticateUser(user, password)
	if !ok {
		w.WriteHeader(http.StatusUnauthorized)
		w.Write([]byte("bad username or password"))
	}

	session, err := s.NewSession()
	if err != nil {
		pages.ServeError500(w)
		log.Error(err)
	}

	http.SetCookie(w, &http.Cookie{
		Name: "phlox-session",
		Value: session,
		Path: "/",
	})
	pages.ServeLoggedIn(w)
}


func LoginGetHandler(
	w http.ResponseWriter,
	r *http.Request,
	s *auth.Sessions,
	pages page.Pages,
) {
	if authenticateRequest(r, s) {
		pages.ServeLoggedIn(w)
	} else {
		pages.ServeLogin(w)
	}
}