-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
86 lines (67 loc) · 2.1 KB
/
auth.go
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
package httpapi
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"github.com/korylprince/bisd-device-checkin-server/v2/session"
)
func (s *Server) authenticate(r *http.Request) (int, interface{}) {
type request struct {
Username string `json:"username"`
Password string `json:"password"`
}
type response struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
SessionID string `json:"session_id"`
}
req := new(request)
if err := jsonRequest(r, req); err != nil {
return http.StatusBadRequest, err
}
user, err := s.auth.Authenticate(req.Username, req.Password)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("Unable to authenticate: %v", err)
}
if user == nil {
return http.StatusUnauthorized, errors.New("Invalid username or password")
}
id, err := s.sessionStore.Create((*session.Session)(user))
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("Unable to create session: %v", err)
}
return http.StatusOK, &response{
Username: user.Username,
DisplayName: user.DisplayName,
SessionID: id,
}
}
func ping(_ *http.Request) (int, interface{}) {
type response struct {
Pong bool `json:"pong"`
}
return http.StatusOK, &response{
Pong: true,
}
}
func withAuth(store session.Store, next returnHandlerFunc) returnHandlerFunc {
return func(r *http.Request) (int, interface{}) {
header := strings.Split(r.Header.Get("Authorization"), " ")
if len(header) != 2 || header[0] != "Bearer" || len(header[1]) != 36 {
return http.StatusBadRequest, errors.New("Invalid Authorization header")
}
session, err := store.Check(header[1])
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("Unexpected error when checking session id %s: %v", header[1], err)
}
if session == nil {
return http.StatusUnauthorized, fmt.Errorf("Session doesn't exist for id %s", header[1])
}
(r.Context().Value(contextKeyLogData)).(*logData).User = session.Username
ctx := context.WithValue(r.Context(), contextKeyUser, session)
status, body := next(r.WithContext(ctx))
return status, body
}
}