2018-06-11 01:15:56 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func commenterLogin(email string, password string) (string, error) {
|
|
|
|
if email == "" || password == "" {
|
|
|
|
return "", errorMissingField
|
|
|
|
}
|
|
|
|
|
|
|
|
statement := `
|
|
|
|
SELECT commenterHex, passwordHash
|
|
|
|
FROM commenters
|
|
|
|
WHERE email = $1 AND provider = 'commento';
|
|
|
|
`
|
|
|
|
row := db.QueryRow(statement, email)
|
|
|
|
|
|
|
|
var commenterHex string
|
|
|
|
var passwordHash string
|
|
|
|
if err := row.Scan(&commenterHex, &passwordHash); err != nil {
|
|
|
|
return "", errorInvalidEmailPassword
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password)); err != nil {
|
|
|
|
// TODO: is this the only possible error?
|
|
|
|
return "", errorInvalidEmailPassword
|
|
|
|
}
|
|
|
|
|
2018-06-20 11:29:55 +08:00
|
|
|
commenterToken, err := randomHex(32)
|
2018-06-11 01:15:56 +08:00
|
|
|
if err != nil {
|
2018-06-20 11:29:55 +08:00
|
|
|
logger.Errorf("cannot create commenterToken: %v", err)
|
2018-06-11 01:15:56 +08:00
|
|
|
return "", errorInternal
|
|
|
|
}
|
|
|
|
|
|
|
|
statement = `
|
|
|
|
INSERT INTO
|
2018-06-20 11:29:55 +08:00
|
|
|
commenterSessions (commenterToken, commenterHex, creationDate)
|
|
|
|
VALUES ($1, $2, $3 );
|
2018-06-11 01:15:56 +08:00
|
|
|
`
|
2018-06-20 11:29:55 +08:00
|
|
|
_, err = db.Exec(statement, commenterToken, commenterHex, time.Now().UTC())
|
2018-06-11 01:15:56 +08:00
|
|
|
if err != nil {
|
2018-06-20 11:29:55 +08:00
|
|
|
logger.Errorf("cannot insert commenterToken token: %v\n", err)
|
2018-06-11 01:15:56 +08:00
|
|
|
return "", errorInternal
|
|
|
|
}
|
|
|
|
|
2018-06-20 11:29:55 +08:00
|
|
|
return commenterToken, nil
|
2018-06-11 01:15:56 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func commenterLoginHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
type request struct {
|
|
|
|
Email *string `json:"email"`
|
|
|
|
Password *string `json:"password"`
|
|
|
|
}
|
|
|
|
|
|
|
|
var x request
|
2018-07-24 14:58:43 +08:00
|
|
|
if err := bodyUnmarshal(r, &x); err != nil {
|
|
|
|
bodyMarshal(w, response{"success": false, "message": err.Error()})
|
2018-06-11 01:15:56 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-06-20 11:29:55 +08:00
|
|
|
commenterToken, err := commenterLogin(*x.Email, *x.Password)
|
2018-06-11 01:15:56 +08:00
|
|
|
if err != nil {
|
2018-07-24 14:58:43 +08:00
|
|
|
bodyMarshal(w, response{"success": false, "message": err.Error()})
|
2018-06-11 01:15:56 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-07-24 14:58:43 +08:00
|
|
|
bodyMarshal(w, response{"success": true, "commenterToken": commenterToken})
|
2018-06-11 01:15:56 +08:00
|
|
|
}
|