2019-02-03 06:57:08 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"encoding/json"
|
2019-04-14 03:38:51 +00:00
|
|
|
"fmt"
|
2019-10-06 02:35:14 +00:00
|
|
|
"git.minhas.io/asara/sudoscientist-go-backend/packages/middleware"
|
2019-05-28 01:17:09 +00:00
|
|
|
"git.minhas.io/asara/sudoscientist-go-backend/packages/users"
|
2019-04-14 03:38:51 +00:00
|
|
|
"github.com/badoux/checkmail"
|
2019-02-03 06:57:08 +00:00
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
|
|
"github.com/go-chi/chi"
|
|
|
|
"github.com/go-chi/jwtauth"
|
|
|
|
"github.com/go-chi/render"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
"net/http"
|
2020-01-19 02:46:46 +00:00
|
|
|
"os"
|
2019-10-06 00:21:48 +00:00
|
|
|
"strings"
|
2019-04-14 03:38:51 +00:00
|
|
|
"time"
|
2019-02-03 06:57:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2020-01-19 02:46:46 +00:00
|
|
|
DB *sql.DB
|
|
|
|
TokenAuth *jwtauth.JWTAuth
|
2020-01-19 05:09:58 +00:00
|
|
|
EmailAuth *jwtauth.JWTAuth
|
2020-01-19 02:46:46 +00:00
|
|
|
PostalEnabled bool
|
|
|
|
PostalKey string
|
|
|
|
PostalAPI string
|
2019-02-03 06:57:08 +00:00
|
|
|
)
|
|
|
|
|
2020-01-19 02:46:46 +00:00
|
|
|
func Init() {
|
|
|
|
if postal_key, ok := os.LookupEnv("POSTAL_KEY"); ok {
|
|
|
|
if postal_api, ok := os.LookupEnv("POSTAL_API"); ok {
|
2020-01-19 05:09:58 +00:00
|
|
|
if email_auth, ok := os.LookupEnv("EMAIL_SECRET"); ok {
|
|
|
|
EmailAuth = jwtauth.New("HS256", []byte(os.Getenv(email_auth)), nil)
|
|
|
|
PostalKey = postal_key
|
|
|
|
PostalAPI = postal_api
|
|
|
|
PostalEnabled = true
|
|
|
|
}
|
2020-01-19 02:46:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-20 21:17:20 +00:00
|
|
|
type ReturnError struct {
|
2019-04-14 03:38:51 +00:00
|
|
|
Message string `json:"error"`
|
|
|
|
}
|
|
|
|
|
2020-01-19 05:09:58 +00:00
|
|
|
type ReturnSuccess struct {
|
|
|
|
Message string `json:"msg"`
|
|
|
|
}
|
|
|
|
|
2019-04-14 03:38:51 +00:00
|
|
|
type SignUpCredentials struct {
|
|
|
|
Username string `json:"username", db:"username"`
|
|
|
|
Email string `json:"email", db:"email"`
|
|
|
|
Password string `json:"password", db:"password"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type SignInCredentials struct {
|
2019-02-03 06:57:08 +00:00
|
|
|
Username string `json:"username", db:"username"`
|
2019-02-07 04:46:30 +00:00
|
|
|
Password string `json:"password", db:"password"`
|
2019-02-03 06:57:08 +00:00
|
|
|
}
|
|
|
|
|
2019-04-14 03:38:51 +00:00
|
|
|
type Claims struct {
|
|
|
|
Username string `json:"username"`
|
|
|
|
jwt.StandardClaims
|
|
|
|
}
|
|
|
|
|
2019-04-14 16:44:02 +00:00
|
|
|
type JWT struct {
|
2019-10-06 00:21:48 +00:00
|
|
|
JWT string `json:"jwt"`
|
2019-02-03 06:57:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func Routes() *chi.Mux {
|
2019-04-14 16:44:02 +00:00
|
|
|
r := chi.NewRouter()
|
|
|
|
r.Post("/signin", signin)
|
|
|
|
r.Post("/register", register)
|
|
|
|
r.Group(func(r chi.Router) {
|
2019-10-06 02:35:14 +00:00
|
|
|
r.Use(jwtauth.Verify(TokenAuth, auth_middleware.TokenFromSplitCookie))
|
2019-04-14 16:44:02 +00:00
|
|
|
r.Use(jwtauth.Authenticator)
|
|
|
|
r.Post("/refresh", refresh)
|
|
|
|
})
|
|
|
|
return r
|
2019-02-03 06:57:08 +00:00
|
|
|
}
|
|
|
|
|
2019-04-14 16:44:02 +00:00
|
|
|
func register(w http.ResponseWriter, r *http.Request) {
|
2019-04-20 21:17:20 +00:00
|
|
|
returnError := ReturnError{}
|
2020-01-19 05:09:58 +00:00
|
|
|
returnSuccess := ReturnSuccess{}
|
2019-04-14 03:38:51 +00:00
|
|
|
creds := &SignUpCredentials{}
|
2019-02-03 06:57:08 +00:00
|
|
|
err := json.NewDecoder(r.Body).Decode(creds)
|
|
|
|
if err != nil {
|
2019-04-14 03:38:51 +00:00
|
|
|
fmt.Println(err)
|
2020-01-19 05:31:21 +00:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
returnError.Message = "unexpected error. please contact the administrator"
|
|
|
|
render.JSON(w, r, returnError)
|
2019-04-14 03:38:51 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if creds.Username == "" {
|
|
|
|
returnError.Message = "username is required"
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
render.JSON(w, r, returnError)
|
2019-02-03 06:57:08 +00:00
|
|
|
return
|
|
|
|
}
|
2019-04-14 03:38:51 +00:00
|
|
|
if creds.Password == "" {
|
|
|
|
returnError.Message = "password is required"
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
render.JSON(w, r, returnError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if creds.Email == "" {
|
|
|
|
returnError.Message = "email is required"
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
render.JSON(w, r, returnError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err = checkmail.ValidateFormat(creds.Email)
|
|
|
|
if err != nil {
|
|
|
|
returnError.Message = "email not valid"
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
render.JSON(w, r, returnError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-02-03 06:57:08 +00:00
|
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10)
|
2020-01-19 05:09:58 +00:00
|
|
|
s := `INSERT INTO users (username, email, password, admin, verified)
|
|
|
|
VALUES ($1, $2, $3, $4, $5)`
|
|
|
|
if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false, false); err != nil {
|
2020-01-19 05:31:21 +00:00
|
|
|
fmt.Println(err)
|
2020-01-19 05:09:58 +00:00
|
|
|
returnError.Message = "unexpected error. please contact the administrator"
|
2019-02-03 06:57:08 +00:00
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
2020-01-19 05:09:58 +00:00
|
|
|
render.JSON(w, r, returnError)
|
2019-02-03 06:57:08 +00:00
|
|
|
return
|
|
|
|
}
|
2019-04-14 03:38:51 +00:00
|
|
|
users.CreateProfile(creds.Username, creds.Email)
|
2020-01-19 05:09:58 +00:00
|
|
|
expirationTime := time.Now().Add(24 * time.Hour)
|
2019-04-14 03:38:51 +00:00
|
|
|
claims := &Claims{
|
|
|
|
Username: creds.Username,
|
|
|
|
StandardClaims: jwt.StandardClaims{
|
|
|
|
ExpiresAt: expirationTime.Unix(),
|
|
|
|
},
|
|
|
|
}
|
2020-01-19 05:09:58 +00:00
|
|
|
if PostalEnabled {
|
|
|
|
_, emailToken, _ := EmailAuth.Encode(claims)
|
|
|
|
w.WriteHeader(http.StatusCreated)
|
|
|
|
//returnSuccess.Message = "User added. Please check your email for a verification link"
|
|
|
|
returnSuccess.Message = emailToken
|
|
|
|
render.JSON(w, r, returnSuccess)
|
|
|
|
return
|
|
|
|
}
|
2019-04-14 03:38:51 +00:00
|
|
|
_, tokenString, _ := TokenAuth.Encode(claims)
|
2020-01-19 05:09:58 +00:00
|
|
|
setCookies(w, tokenString, expirationTime)
|
|
|
|
w.WriteHeader(http.StatusCreated)
|
|
|
|
returnSuccess.Message = "User created! Welcome to the site!"
|
|
|
|
render.JSON(w, r, returnSuccess)
|
|
|
|
return
|
2019-02-03 06:57:08 +00:00
|
|
|
}
|
|
|
|
|
2019-02-08 04:43:26 +00:00
|
|
|
func signin(w http.ResponseWriter, r *http.Request) {
|
2019-04-14 03:38:51 +00:00
|
|
|
creds := &SignInCredentials{}
|
2019-02-03 06:57:08 +00:00
|
|
|
err := json.NewDecoder(r.Body).Decode(creds)
|
|
|
|
if err != nil {
|
|
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
result := DB.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username)
|
2019-04-14 03:38:51 +00:00
|
|
|
storedCreds := &SignInCredentials{}
|
2019-02-03 06:57:08 +00:00
|
|
|
err = result.Scan(&storedCreds.Password)
|
|
|
|
if err != nil {
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
}
|
2020-01-19 05:09:58 +00:00
|
|
|
expirationTime := time.Now().Add(24 * time.Hour)
|
2019-04-14 03:38:51 +00:00
|
|
|
claims := &Claims{
|
|
|
|
Username: creds.Username,
|
|
|
|
StandardClaims: jwt.StandardClaims{
|
|
|
|
ExpiresAt: expirationTime.Unix(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
_, tokenString, _ := TokenAuth.Encode(claims)
|
2019-10-06 00:21:48 +00:00
|
|
|
token := setCookies(w, tokenString, expirationTime)
|
|
|
|
w.WriteHeader(http.StatusOK)
|
2019-04-14 16:44:02 +00:00
|
|
|
render.JSON(w, r, token)
|
|
|
|
}
|
|
|
|
|
|
|
|
func refresh(w http.ResponseWriter, r *http.Request) {
|
|
|
|
_, claims, _ := jwtauth.FromContext(r.Context())
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
expirationTime := time.Now().Add(5 * time.Hour)
|
2019-04-14 17:29:15 +00:00
|
|
|
newClaims := &Claims{
|
2019-04-14 16:44:02 +00:00
|
|
|
Username: claims["username"].(string),
|
|
|
|
StandardClaims: jwt.StandardClaims{
|
|
|
|
ExpiresAt: expirationTime.Unix(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
_, tokenString, _ := TokenAuth.Encode(newClaims)
|
2019-10-06 00:21:48 +00:00
|
|
|
token := setCookies(w, tokenString, expirationTime)
|
|
|
|
w.WriteHeader(http.StatusOK)
|
2019-04-14 03:38:51 +00:00
|
|
|
render.JSON(w, r, token)
|
2019-02-03 06:57:08 +00:00
|
|
|
}
|
2019-10-06 00:21:48 +00:00
|
|
|
|
|
|
|
func setCookies(w http.ResponseWriter, jwt string, expiration time.Time) string {
|
|
|
|
splitToken := strings.Split(jwt, ".")
|
2019-10-06 02:50:48 +00:00
|
|
|
dataCookie := http.Cookie{Name: "DataCookie", Value: strings.Join(splitToken[:2], "."), Expires: expiration, HttpOnly: false, Path: "/", Domain: ".sudoscientist.com", MaxAge: 360, Secure: true}
|
2019-10-06 00:21:48 +00:00
|
|
|
http.SetCookie(w, &dataCookie)
|
2019-10-06 02:50:48 +00:00
|
|
|
signatureCookie := http.Cookie{Name: "SignatureCookie", Value: splitToken[2], Expires: expiration, HttpOnly: true, Path: "/", Domain: ".sudoscientist.com", MaxAge: 360, Secure: true}
|
2019-10-06 00:21:48 +00:00
|
|
|
http.SetCookie(w, &signatureCookie)
|
|
|
|
return strings.Join(splitToken[:2], ".")
|
|
|
|
}
|