-
Notifications
You must be signed in to change notification settings - Fork 0
/
login.go
65 lines (54 loc) · 1.39 KB
/
login.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
package handlers
import (
"encoding/json"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/udacity/ud615/app/user"
"golang.org/x/crypto/bcrypt"
)
type LoginResponse struct {
Token string `json:"token"`
}
type loginHandler struct {
secret string
users user.Users
}
func (h *loginHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
user, ok := h.users[username]
if !ok {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
if err != nil {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
token.Claims["iss"] = "auth.service"
token.Claims["iat"] = time.Now().Unix()
token.Claims["email"] = user.Email
token.Claims["sub"] = user.Username
tokenString, err := token.SignedString([]byte(h.secret))
if err != nil {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
response := LoginResponse{
Token: tokenString,
}
json.NewEncoder(w).Encode(response)
}
func LoginHandler(secret string, users user.Users) http.Handler {
return &loginHandler{
secret: secret,
users: users,
}
}