-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
49 lines (40 loc) · 1.36 KB
/
token.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
package auth
import (
"encoding/json"
"errors"
"github.com/kidstuff/auth/authmodel"
"net/http"
"time"
)
// GetToken handle 'login' action. The token return use to verify later reuqest.
// Details: http://kidstuff.github.io/swagger/#!/default/tokens_get
func GetToken(authCtx *AuthContext, rw http.ResponseWriter, req *http.Request) (int, error) {
grantType := req.FormValue("grant_type")
email := req.FormValue("email")
password := req.FormValue("password")
// TODO: more detail error message
if len(grantType) == 0 || len(email) == 0 || len(password) == 0 {
return http.StatusBadRequest, errors.New("kidstuff/auth: grant_type, email and password need to be set.")
}
if grantType != "password" {
return http.StatusBadRequest, errors.New("kidstuff/auth: Only support grant_type=password")
}
user, err := authCtx.Auth.FindUserByEmail(email)
if err != nil {
return http.StatusUnauthorized, ErrInvalidCredential
}
err = authCtx.Auth.ComparePassword(password, user.Pwd)
if err != nil {
return http.StatusUnauthorized, ErrInvalidCredential
}
token, err := authCtx.Auth.Login(*user.Id, OnlineThreshold)
if err != nil {
return http.StatusInternalServerError, err
}
inf := struct {
User *authmodel.User
ExpiredOn time.Time
AccessToken string
}{user, time.Now().Add(OnlineThreshold), token}
return http.StatusOK, json.NewEncoder(rw).Encode(&inf)
}