2021-12-25 02:16:58 +01:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"orblivion/lbry-id/auth"
|
|
|
|
"orblivion/lbry-id/store"
|
|
|
|
)
|
|
|
|
|
2022-06-07 19:25:14 +02:00
|
|
|
// DeviceId is decided by the device. UserId is decided by the server, and is
|
|
|
|
// gatekept by Email/Password
|
2022-06-08 00:24:01 +02:00
|
|
|
type AuthRequest struct {
|
2022-06-07 19:25:14 +02:00
|
|
|
DeviceId auth.DeviceId `json:"deviceId"`
|
|
|
|
Email auth.Email `json:"email"`
|
|
|
|
Password auth.Password `json:"password"`
|
2021-12-25 02:16:58 +01:00
|
|
|
}
|
|
|
|
|
2022-06-08 02:08:41 +02:00
|
|
|
// TODO - validate funcs probably should return error rather than bool for
|
|
|
|
// idiomatic golang
|
2022-06-08 00:24:01 +02:00
|
|
|
func (r *AuthRequest) validate() bool {
|
2022-06-17 22:12:20 +02:00
|
|
|
return r.DeviceId != "" && r.Password != auth.Password("") && validateEmail(r.Email)
|
2021-12-25 02:16:58 +01:00
|
|
|
}
|
|
|
|
|
2022-06-08 00:24:01 +02:00
|
|
|
func (s *Server) getAuthToken(w http.ResponseWriter, req *http.Request) {
|
|
|
|
var authRequest AuthRequest
|
2021-12-25 02:16:58 +01:00
|
|
|
if !getPostData(w, req, &authRequest) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-06-07 19:25:14 +02:00
|
|
|
userId, err := s.store.GetUserId(authRequest.Email, authRequest.Password)
|
2022-07-06 18:44:35 +02:00
|
|
|
if err == store.ErrWrongCredentials {
|
2022-06-07 19:25:14 +02:00
|
|
|
errorJson(w, http.StatusUnauthorized, "No match for email and password")
|
2021-12-25 02:16:58 +01:00
|
|
|
return
|
|
|
|
}
|
2022-06-07 19:25:14 +02:00
|
|
|
if err != nil {
|
|
|
|
internalServiceErrorJson(w, err, "Error getting User Id")
|
2021-12-25 02:16:58 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-06-07 19:25:14 +02:00
|
|
|
authToken, err := s.auth.NewToken(userId, authRequest.DeviceId, auth.ScopeFull)
|
2021-12-25 02:16:58 +01:00
|
|
|
|
|
|
|
if err != nil {
|
2022-06-07 19:25:14 +02:00
|
|
|
internalServiceErrorJson(w, err, "Error generating auth token")
|
2021-12-25 02:16:58 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
response, err := json.Marshal(&authToken)
|
|
|
|
|
|
|
|
if err != nil {
|
2022-06-07 19:25:14 +02:00
|
|
|
internalServiceErrorJson(w, err, "Error generating auth token")
|
2021-12-25 02:16:58 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.store.SaveToken(authToken); err != nil {
|
2022-06-07 19:25:14 +02:00
|
|
|
internalServiceErrorJson(w, err, "Error saving auth token")
|
2021-12-25 02:16:58 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprintf(w, string(response))
|
|
|
|
}
|