-
Notifications
You must be signed in to change notification settings - Fork 0
/
loginHandler.go
64 lines (54 loc) · 1.64 KB
/
loginHandler.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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/PratikforCoding/chirpy.git/internal/auth"
)
func (cfg *apiConfig) handlerLogin(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Password string `json:"password"`
Email string `json:"email"`
}
type returnUser struct {
ID int `json:"id"`
Email string `json:"email"`
AccessToken string `json:"access-token"`
RefreshToken string `json:"refresh-token"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
responseWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
user, err := cfg.DB.GetUserByEmail(params.Email)
if err != nil {
responseWithError(w, http.StatusInternalServerError, "Couldn't get user")
return
}
err = auth.CheckPasswordHash(params.Password, user.HashedPassword)
if err != nil {
responseWithError(w, http.StatusUnauthorized, "Invalid password")
return
}
accessTokenTime := 60 * 60
refreshTokenTime := 60 * 24 * 60 * 60
accessToken, err := auth.MakeAccessToken(user.ID, cfg.jwt_secret, time.Duration(accessTokenTime) * time.Second)
if err != nil {
responseWithError(w, http.StatusInternalServerError, "Couldn't not create Access Token")
return
}
refreshToken, err := auth.MakeRefreshToken(user.ID, cfg.jwt_secret, time.Duration(refreshTokenTime) * time.Second)
if err != nil {
responseWithError(w, http.StatusInternalServerError, "Couldn't not create Access Token")
return
}
responseWithJson(w, http.StatusOK, returnUser{
ID: user.ID,
Email: user.Email,
AccessToken: accessToken,
RefreshToken: refreshToken,
})
}