This repository has been archived by the owner on Sep 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_handler.go
150 lines (141 loc) · 4.46 KB
/
auth_handler.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package starter
import (
"crypto/rand"
"fmt"
"net/http"
"strings"
"github.com/fossapps/starter/config"
"github.com/fossapps/starter/transformer"
"github.com/globalsign/mgo"
"github.com/gorilla/mux"
"golang.org/x/crypto/bcrypt"
"gopkg.in/matryer/respond.v1"
)
// LoginResponse responds with this type when login is successful
type LoginResponse struct {
JWT string `json:"jwt"`
RefreshToken string `json:"refresh_token"`
}
// RefreshTokenHandlerResponse is used when a refresh token is requested
type RefreshTokenHandlerResponse struct {
JWT string `json:"jwt"`
}
// LoginHandler handles login requests
func (s *Server) LoginHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
email, password, ok := r.BasicAuth()
if !ok {
s.Logger.Warn("basic auth not present")
s.ErrorResponse(w, r, http.StatusUnauthorized, "unauthorized")
return
}
dbLayer := s.Db.Clone()
defer dbLayer.Close()
user, err := dbLayer.Users().FindByEmail(email)
if err != nil {
s.ErrorResponse(w, r, http.StatusInternalServerError, "server error")
return
}
if user == nil {
s.ErrorResponse(w, r, http.StatusBadRequest, "invalid credentials")
return
}
err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
if err != nil {
s.ErrorResponse(w, r, http.StatusUnauthorized, "invalid credentials")
return
}
jwtToken, err := s.Jwt.CreateForUser(user)
if err != nil {
s.Logger.Error("jwt error", err)
s.ErrorResponse(w, r, http.StatusInternalServerError, "error generating token")
return
}
refreshToken := getRefreshToken(config.GetApplicationConfig().RefreshTokenSize)
res := LoginResponse{
JWT: jwtToken,
RefreshToken: refreshToken,
}
dbLayer.RefreshTokens().Add(res.RefreshToken, user.ID.Hex())
respond.With(w, r, http.StatusOK, res)
})
}
// RefreshTokenHandler is used to refresh token
func (s *Server) RefreshTokenHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
token := strings.TrimPrefix(authHeader, "Bearer ")
if token == "" {
s.ErrorResponse(w, r, http.StatusBadRequest, "token missing")
return
}
dbLayer := s.Db.Clone()
defer dbLayer.Close()
refreshToken, err := dbLayer.RefreshTokens().FindOne(token)
if err != nil {
s.ErrorResponse(w, r, http.StatusInternalServerError, "server error")
return
}
if refreshToken == nil {
s.ErrorResponse(w, r, http.StatusUnauthorized, "invalid refresh token")
return
}
user, err := dbLayer.Users().FindByID(refreshToken.User)
if err != nil {
s.ErrorResponse(w, r, http.StatusInternalServerError, "server error")
return
}
if user == nil {
// todo shouldn't have happened, log
s.Logger.Warn("refresh token found in collection, but user is nil: ", refreshToken)
s.ErrorResponse(w, r, http.StatusUnauthorized, "invalid refresh token")
return
}
token, err = s.Jwt.CreateForUser(user)
if err != nil {
s.Logger.Error("token generation error: ", err)
s.ErrorResponse(w, r, http.StatusInternalServerError, "error generating token")
return
}
respond.With(w, r, http.StatusOK, RefreshTokenHandlerResponse{JWT: token})
})
}
// RefreshTokensList returns list of refresh token associated with a user
func (s *Server) RefreshTokensList() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, err := s.Jwt.GetJwtDataFromRequest(r)
if err != nil {
s.ErrorResponse(w, r, http.StatusBadRequest, "error parsing token")
return
}
user := claims.ID
database := s.Db.Clone()
tokens, err := database.RefreshTokens().List(user)
if err != nil {
s.ErrorResponse(w, r, http.StatusInternalServerError, "database error")
return
}
respond.With(w, r, http.StatusOK, transformer.TransformRefreshTokens(tokens))
})
}
// DeleteSession deletes a session, used for logging out
func (s *Server) DeleteSession() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := mux.Vars(r)["token"]
err := s.Db.RefreshTokens().Delete(token)
if err != nil && err.Error() == mgo.ErrNotFound.Error() {
http.NotFound(w, r)
return
}
if err != nil {
s.ErrorResponse(w, r, http.StatusInternalServerError, "db error")
return
}
respond.With(w, r, http.StatusNoContent, nil)
})
}
func getRefreshToken(length int) string {
b := make([]byte, length)
rand.Read(b)
return fmt.Sprintf("%x", b)
}