Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.6 KiB

package Auth
import (
"database/sql/driver"
"encoding/json"
"net/http"
"time"
"git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
)
type signup struct {
Username string `json:"username"`
Password string `json:"password"`
ConfirmPassword string `json:"confirm_password"`
PublicKey string `json:"asymmetric_public_key"`
PrivateKey string `json:"asymmetric_private_key"`
}
// Signup to the platform
func Signup(w http.ResponseWriter, r *http.Request) {
var (
user Database.User
expiresAt time.Time
session Database.Session
messageExpiryRaw driver.Value
messageExpiry string
imageLink string
returnJSON []byte
err error
)
err = json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
return
}
if user.Username == "" ||
user.Password == "" ||
user.ConfirmPassword == "" ||
len(user.AsymmetricPrivateKey) == 0 ||
len(user.AsymmetricPublicKey) == 0 {
http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
return
}
if user.Password != user.ConfirmPassword {
http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
return
}
err = Database.CheckUniqueUsername(user.Username)
if err != nil {
http.Error(w, "Invalid Data", http.StatusUnprocessableEntity)
return
}
user.Password, err = HashPassword(user.Password)
if err != nil {
http.Error(w, "Error", http.StatusInternalServerError)
return
}
err = (&user).CreateUser()
if err != nil {
http.Error(w, "Error", http.StatusInternalServerError)
return
}
// TODO: Revisit before production
expiresAt = time.Now().Add(12 * time.Hour)
session = Database.Session{
UserID: user.ID,
Expiry: expiresAt,
}
err = (&session).CreateSession()
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
http.SetCookie(w, &http.Cookie{
Name: "session_token",
Value: session.ID.String(),
Expires: expiresAt,
})
if user.AttachmentID != nil {
imageLink = user.Attachment.FilePath
}
messageExpiryRaw, _ = user.MessageExpiryDefault.Value()
messageExpiry, _ = messageExpiryRaw.(string)
returnJSON, err = json.MarshalIndent(loginResponse{
UserID: user.ID.String(),
Username: user.Username,
AsymmetricPublicKey: user.AsymmetricPublicKey,
AsymmetricPrivateKey: user.AsymmetricPrivateKey,
SymmetricKey: user.SymmetricKey,
MessageExpiryDefault: messageExpiry,
ImageLink: imageLink,
}, "", " ")
w.WriteHeader(http.StatusOK)
w.Write(returnJSON)
}