2021-12-25 02:16:58 +01:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2022-07-13 18:32:48 +02:00
|
|
|
|
2022-07-12 04:10:19 +02:00
|
|
|
"lbryio/lbry-id/auth"
|
|
|
|
"lbryio/lbry-id/store"
|
2021-12-25 02:16:58 +01:00
|
|
|
)
|
|
|
|
|
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-07-11 15:42:08 +02:00
|
|
|
func (r *AuthRequest) validate() error {
|
2022-07-24 22:02:55 +02:00
|
|
|
if !r.Email.Validate() {
|
2022-07-11 15:42:08 +02:00
|
|
|
return fmt.Errorf("Invalid 'email'")
|
|
|
|
}
|
|
|
|
if r.Password == "" {
|
|
|
|
return fmt.Errorf("Missing 'password'")
|
|
|
|
}
|
|
|
|
if r.DeviceId == "" {
|
|
|
|
return fmt.Errorf("Missing 'deviceId'")
|
|
|
|
}
|
|
|
|
return nil
|
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-07-26 16:53:31 +02:00
|
|
|
if err == store.ErrNotVerified {
|
|
|
|
errorJson(w, http.StatusUnauthorized, "Account is not verified")
|
|
|
|
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-07-28 01:45:09 +02:00
|
|
|
authToken, err := s.auth.NewAuthToken(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))
|
|
|
|
}
|