-
Notifications
You must be signed in to change notification settings - Fork 19
/
login.go
87 lines (70 loc) · 2.4 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package app
import (
// Those imports are required to compute the secret hash.
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/aws/aws-sdk-go/aws"
cognito "github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
)
const flowUsernamePassword = "USER_PASSWORD_AUTH"
const flowRefreshToken = "REFRESH_TOKEN_AUTH"
// Secret hash is not a client secret itself, but a base64 encoded hmac-sha256
// hash.
// The actual AWS documentation on how to compute this hash is here:
// https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html#cognito-user-pools-computing-secret-hash
func computeSecretHash(clientSecret string, username string, clientId string) string {
mac := hmac.New(sha256.New, []byte(clientSecret))
mac.Write([]byte(username + clientId))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
// Login handles login scenario.
func (a *App) Login(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.Form.Get("username")
password := r.Form.Get("password")
refresh := r.Form.Get("refresh")
refreshToken := r.Form.Get("refresh_token")
flow := aws.String(flowUsernamePassword)
params := map[string]*string{
"USERNAME": aws.String(username),
"PASSWORD": aws.String(password),
}
// Compute secret hash based on client secret.
if a.AppClientSecret != "" {
secretHash := computeSecretHash(a.AppClientSecret, username, a.AppClientID)
params["SECRET_HASH"] = aws.String(secretHash)
}
if refresh != "" {
flow = aws.String(flowRefreshToken)
params = map[string]*string{
"REFRESH_TOKEN": aws.String(refreshToken),
}
}
authTry := &cognito.InitiateAuthInput{
AuthFlow: flow,
AuthParameters: params,
ClientId: aws.String(a.AppClientID),
}
res, err := a.CognitoClient.InitiateAuth(authTry)
if err != nil {
fmt.Println(err)
http.Redirect(w, r, fmt.Sprintf("/login?message=%s", err.Error()), http.StatusSeeOther)
return
}
if res.ChallengeName != nil && *res.ChallengeName == "NEW_PASSWORD_REQUIRED" {
params = map[string]*string{
"username": aws.String(username),
"session": res.Session,
}
b, _ := json.Marshal(params)
s := url.QueryEscape(string(b))
http.Redirect(w, r, fmt.Sprintf("/new_password_required?params=%s", s), http.StatusFound)
return
}
http.Redirect(w, r, fmt.Sprintf("/login?authres=%s", res.AuthenticationResult), http.StatusFound)
}