191 lines
5.2 KiB
Go
191 lines
5.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"git.minhas.io/asara/sudoscientist-go-backend/packages/middleware"
|
|
"git.minhas.io/asara/sudoscientist-go-backend/packages/users"
|
|
"github.com/badoux/checkmail"
|
|
"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"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
DB *sql.DB
|
|
TokenAuth *jwtauth.JWTAuth
|
|
PostalEnabled bool
|
|
PostalKey string
|
|
PostalAPI string
|
|
)
|
|
|
|
func Init() {
|
|
if postal_key, ok := os.LookupEnv("POSTAL_KEY"); ok {
|
|
PostalKey = postal_key
|
|
if postal_api, ok := os.LookupEnv("POSTAL_API"); ok {
|
|
PostalAPI = postal_api
|
|
PostalEnabled = true
|
|
}
|
|
}
|
|
}
|
|
|
|
type ReturnError struct {
|
|
Message string `json:"error"`
|
|
}
|
|
|
|
type SignUpCredentials struct {
|
|
Username string `json:"username", db:"username"`
|
|
Email string `json:"email", db:"email"`
|
|
Password string `json:"password", db:"password"`
|
|
}
|
|
|
|
type SignInCredentials struct {
|
|
Username string `json:"username", db:"username"`
|
|
Password string `json:"password", db:"password"`
|
|
}
|
|
|
|
type Claims struct {
|
|
Username string `json:"username"`
|
|
jwt.StandardClaims
|
|
}
|
|
|
|
type JWT struct {
|
|
JWT string `json:"jwt"`
|
|
}
|
|
|
|
func Routes() *chi.Mux {
|
|
r := chi.NewRouter()
|
|
r.Post("/signin", signin)
|
|
r.Post("/register", register)
|
|
r.Group(func(r chi.Router) {
|
|
r.Use(jwtauth.Verify(TokenAuth, auth_middleware.TokenFromSplitCookie))
|
|
r.Use(jwtauth.Authenticator)
|
|
r.Post("/refresh", refresh)
|
|
})
|
|
return r
|
|
}
|
|
|
|
func register(w http.ResponseWriter, r *http.Request) {
|
|
returnError := ReturnError{}
|
|
creds := &SignUpCredentials{}
|
|
err := json.NewDecoder(r.Body).Decode(creds)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
if creds.Username == "" {
|
|
returnError.Message = "username is required"
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
render.JSON(w, r, returnError)
|
|
return
|
|
}
|
|
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
|
|
}
|
|
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), 10)
|
|
s := `INSERT INTO users (username, email, password, admin)
|
|
VALUES ($1, $2, $3, $4)`
|
|
if _, err = DB.Exec(s, creds.Username, creds.Email, string(hashedPassword), false); err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
fmt.Println(err)
|
|
return
|
|
}
|
|
users.CreateProfile(creds.Username, creds.Email)
|
|
w.WriteHeader(http.StatusCreated)
|
|
expirationTime := time.Now().Add(6 * time.Hour)
|
|
claims := &Claims{
|
|
Username: creds.Username,
|
|
StandardClaims: jwt.StandardClaims{
|
|
ExpiresAt: expirationTime.Unix(),
|
|
},
|
|
}
|
|
_, tokenString, _ := TokenAuth.Encode(claims)
|
|
token := setCookies(w, tokenString, expirationTime)
|
|
w.WriteHeader(http.StatusOK)
|
|
render.JSON(w, r, token)
|
|
}
|
|
|
|
func signin(w http.ResponseWriter, r *http.Request) {
|
|
creds := &SignInCredentials{}
|
|
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)
|
|
storedCreds := &SignInCredentials{}
|
|
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)
|
|
}
|
|
expirationTime := time.Now().Add(5 * time.Hour)
|
|
claims := &Claims{
|
|
Username: creds.Username,
|
|
StandardClaims: jwt.StandardClaims{
|
|
ExpiresAt: expirationTime.Unix(),
|
|
},
|
|
}
|
|
_, tokenString, _ := TokenAuth.Encode(claims)
|
|
token := setCookies(w, tokenString, expirationTime)
|
|
w.WriteHeader(http.StatusOK)
|
|
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)
|
|
newClaims := &Claims{
|
|
Username: claims["username"].(string),
|
|
StandardClaims: jwt.StandardClaims{
|
|
ExpiresAt: expirationTime.Unix(),
|
|
},
|
|
}
|
|
_, tokenString, _ := TokenAuth.Encode(newClaims)
|
|
token := setCookies(w, tokenString, expirationTime)
|
|
w.WriteHeader(http.StatusOK)
|
|
render.JSON(w, r, token)
|
|
}
|
|
|
|
func setCookies(w http.ResponseWriter, jwt string, expiration time.Time) string {
|
|
splitToken := strings.Split(jwt, ".")
|
|
dataCookie := http.Cookie{Name: "DataCookie", Value: strings.Join(splitToken[:2], "."), Expires: expiration, HttpOnly: false, Path: "/", Domain: ".sudoscientist.com", MaxAge: 360, Secure: true}
|
|
http.SetCookie(w, &dataCookie)
|
|
signatureCookie := http.Cookie{Name: "SignatureCookie", Value: splitToken[2], Expires: expiration, HttpOnly: true, Path: "/", Domain: ".sudoscientist.com", MaxAge: 360, Secure: true}
|
|
http.SetCookie(w, &signatureCookie)
|
|
return strings.Join(splitToken[:2], ".")
|
|
}
|