2018-01-23 10:48:44 +00:00
package routes
import (
2018-05-31 06:51:31 +00:00
"crypto/sha256"
2018-06-17 07:28:18 +00:00
"crypto/subtle"
2018-05-14 08:56:56 +00:00
"database/sql"
2018-05-31 06:51:31 +00:00
"encoding/hex"
2019-03-11 08:47:45 +00:00
"html"
2018-05-14 08:56:56 +00:00
"io"
2018-02-03 05:47:14 +00:00
"log"
2018-10-10 07:33:51 +00:00
"math"
2018-01-23 10:48:44 +00:00
"net/http"
2018-05-14 08:56:56 +00:00
"os"
"regexp"
2018-03-17 08:16:43 +00:00
"strconv"
2018-02-03 05:47:14 +00:00
"strings"
2018-01-23 10:48:44 +00:00
2019-04-19 06:36:26 +00:00
c "github.com/Azareal/Gosora/common"
2018-11-01 06:43:56 +00:00
"github.com/Azareal/Gosora/common/phrases"
2018-11-12 09:23:36 +00:00
"github.com/Azareal/Gosora/query_gen"
2018-01-23 10:48:44 +00:00
)
// A blank list to fill out that parameter in Page for routes which don't use it
var tList [ ] interface { }
2019-04-19 06:36:26 +00:00
func AccountLogin ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-02-03 05:47:14 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2018-02-03 05:47:14 +00:00
}
2018-11-01 06:43:56 +00:00
header . Title = phrases . GetTitlePhrase ( "login" )
2019-04-19 09:34:16 +00:00
return renderTemplate ( "login" , w , r , header , c . Page { header , tList , nil } )
2018-02-03 05:47:14 +00:00
}
// TODO: Log failed attempted logins?
// TODO: Lock IPS out if they have too many failed attempts?
// TODO: Log unusual countries in comparison to the country a user usually logs in from? Alert the user about this?
2019-04-19 06:36:26 +00:00
func AccountLoginSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
2018-02-03 05:47:14 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2018-02-03 05:47:14 +00:00
}
2019-04-19 06:36:26 +00:00
username := c . SanitiseSingleLine ( r . PostFormValue ( "username" ) )
uid , err , requiresExtraAuth := c . Auth . Authenticate ( username , r . PostFormValue ( "password" ) )
2018-02-03 05:47:14 +00:00
if err != nil {
2018-12-17 04:58:55 +00:00
{
// TODO: uid is currently set to 0 as authenticate fetches the user by username and password. Get the actual uid, so we can alert the user of attempted logins? What if someone takes advantage of the response times to deduce if an account exists?
2019-04-19 06:36:26 +00:00
logItem := & c . LoginLogItem { UID : uid , Success : false , IPAddress : user . LastIP }
2018-12-17 04:58:55 +00:00
_ , err := logItem . Create ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-12-17 04:58:55 +00:00
}
}
2019-04-19 06:36:26 +00:00
return c . LocalError ( err . Error ( ) , w , r , user )
2018-02-03 05:47:14 +00:00
}
2018-12-17 04:58:55 +00:00
// TODO: Take 2FA into account
2019-04-19 06:36:26 +00:00
logItem := & c . LoginLogItem { UID : uid , Success : true , IPAddress : user . LastIP }
2018-12-17 04:58:55 +00:00
_ , err = logItem . Create ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-12-17 04:58:55 +00:00
}
2018-06-17 07:28:18 +00:00
// TODO: Do we want to slacken this by only doing it when the IP changes?
if requiresExtraAuth {
2019-04-19 06:36:26 +00:00
provSession , signedSession , err := c . Auth . CreateProvisionalSession ( uid )
2018-06-17 07:28:18 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
}
2018-12-17 04:58:55 +00:00
// TODO: Use the login log ID in the provisional cookie?
2019-04-19 06:36:26 +00:00
c . Auth . SetProvisionalCookies ( w , uid , provSession , signedSession )
2018-06-17 07:28:18 +00:00
http . Redirect ( w , r , "/accounts/mfa_verify/" , http . StatusSeeOther )
return nil
}
2018-02-03 05:47:14 +00:00
2018-06-17 07:28:18 +00:00
return loginSuccess ( uid , w , r , & user )
}
2019-04-19 06:36:26 +00:00
func loginSuccess ( uid int , w http . ResponseWriter , r * http . Request , user * c . User ) c . RouteError {
userPtr , err := c . Users . Get ( uid )
2018-02-03 05:47:14 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Bad account" , w , r , * user )
2018-02-03 05:47:14 +00:00
}
2018-06-17 07:28:18 +00:00
* user = * userPtr
2018-02-03 05:47:14 +00:00
var session string
if user . Session == "" {
2019-04-19 06:36:26 +00:00
session , err = c . Auth . CreateSession ( uid )
2018-02-03 05:47:14 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-02-03 05:47:14 +00:00
}
} else {
session = user . Session
}
2019-04-19 06:36:26 +00:00
c . Auth . SetCookies ( w , uid , session )
2018-02-03 05:47:14 +00:00
if user . IsAdmin {
// Is this error check redundant? We already check for the error in PreRoute for the same IP
// TODO: Should we be logging this?
log . Printf ( "#%d has logged in with IP %s" , uid , user . LastIP )
}
http . Redirect ( w , r , "/" , http . StatusSeeOther )
return nil
}
2018-06-17 07:28:18 +00:00
func extractCookie ( name string , r * http . Request ) ( string , error ) {
cookie , err := r . Cookie ( name )
if err != nil {
return "" , err
}
return cookie . Value , nil
}
func mfaGetCookies ( r * http . Request ) ( uid int , provSession string , signedSession string , err error ) {
suid , err := extractCookie ( "uid" , r )
if err != nil {
return 0 , "" , "" , err
}
uid , err = strconv . Atoi ( suid )
if err != nil {
return 0 , "" , "" , err
}
provSession , err = extractCookie ( "provSession" , r )
if err != nil {
return 0 , "" , "" , err
}
signedSession , err = extractCookie ( "signedSession" , r )
return uid , provSession , signedSession , err
}
func mfaVerifySession ( provSession string , signedSession string , uid int ) bool {
h := sha256 . New ( )
2019-04-19 06:36:26 +00:00
h . Write ( [ ] byte ( c . SessionSigningKeyBox . Load ( ) . ( string ) ) )
2018-06-17 07:28:18 +00:00
h . Write ( [ ] byte ( provSession ) )
h . Write ( [ ] byte ( strconv . Itoa ( uid ) ) )
expected := hex . EncodeToString ( h . Sum ( nil ) )
if subtle . ConstantTimeCompare ( [ ] byte ( signedSession ) , [ ] byte ( expected ) ) == 1 {
return true
}
h = sha256 . New ( )
2019-04-19 06:36:26 +00:00
h . Write ( [ ] byte ( c . OldSessionSigningKeyBox . Load ( ) . ( string ) ) )
2018-06-17 07:28:18 +00:00
h . Write ( [ ] byte ( provSession ) )
h . Write ( [ ] byte ( strconv . Itoa ( uid ) ) )
expected = hex . EncodeToString ( h . Sum ( nil ) )
return subtle . ConstantTimeCompare ( [ ] byte ( signedSession ) , [ ] byte ( expected ) ) == 1
}
2019-04-19 06:36:26 +00:00
func AccountLoginMFAVerify ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-06-17 07:28:18 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2018-06-17 07:28:18 +00:00
}
2018-11-01 06:43:56 +00:00
header . Title = phrases . GetTitlePhrase ( "login_mfa_verify" )
2018-06-17 07:28:18 +00:00
uid , provSession , signedSession , err := mfaGetCookies ( r )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Invalid cookie" , w , r , user )
2018-06-17 07:28:18 +00:00
}
if ! mfaVerifySession ( provSession , signedSession , uid ) {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Invalid session" , w , r , user )
2018-06-17 07:28:18 +00:00
}
2019-04-19 09:34:16 +00:00
return renderTemplate ( "login_mfa_verify" , w , r , header , c . Page { header , tList , nil } )
2018-06-17 07:28:18 +00:00
}
2019-04-19 06:36:26 +00:00
func AccountLoginMFAVerifySubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
2018-06-17 07:28:18 +00:00
uid , provSession , signedSession , err := mfaGetCookies ( r )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Invalid cookie" , w , r , user )
2018-06-17 07:28:18 +00:00
}
if ! mfaVerifySession ( provSession , signedSession , uid ) {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Invalid session" , w , r , user )
2018-06-17 07:28:18 +00:00
}
var token = r . PostFormValue ( "mfa_token" )
2019-04-19 06:36:26 +00:00
err = c . Auth . ValidateMFAToken ( token , uid )
2018-06-17 07:28:18 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( err . Error ( ) , w , r , user )
2018-06-17 07:28:18 +00:00
}
return loginSuccess ( uid , w , r , & user )
}
2019-04-19 06:36:26 +00:00
func AccountLogout ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
c . Auth . Logout ( w , user . ID )
2018-05-15 05:59:52 +00:00
http . Redirect ( w , r , "/" , http . StatusSeeOther )
return nil
}
2019-04-19 06:36:26 +00:00
func AccountRegister ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-02-03 05:47:14 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2018-02-03 05:47:14 +00:00
}
2018-11-01 06:43:56 +00:00
header . Title = phrases . GetTitlePhrase ( "register" )
2019-04-25 06:02:51 +00:00
header . AddScriptAsync ( "register.js" )
2019-04-19 09:34:16 +00:00
return renderTemplate ( "register" , w , r , header , c . Page { header , tList , nil } )
2018-02-03 05:47:14 +00:00
}
2018-09-20 04:36:50 +00:00
func isNumeric ( data string ) ( numeric bool ) {
for _ , char := range data {
if char < 48 || char > 57 {
return false
}
}
return true
}
2019-04-19 06:36:26 +00:00
func AccountRegisterSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
headerLite , _ := c . SimpleUserCheck ( w , r , & user )
2018-02-03 05:47:14 +00:00
2018-05-16 10:46:14 +00:00
// TODO: Should we push multiple validation errors to the user instead of just one?
var regSuccess = true
var regErrMsg = ""
var regErrReason = ""
var regError = func ( userMsg string , reason string ) {
regSuccess = false
if regErrMsg == "" {
regErrMsg = userMsg
}
regErrReason += reason + "|"
}
2018-05-31 06:51:31 +00:00
if r . PostFormValue ( "tos" ) != "0" {
2018-11-01 06:43:56 +00:00
regError ( phrases . GetErrorPhrase ( "register_might_be_machine" ) , "trap-question" )
2018-05-31 06:51:31 +00:00
}
2019-04-19 06:36:26 +00:00
if ! c . Config . DisableJSAntispam {
2018-10-16 10:02:51 +00:00
h := sha256 . New ( )
2019-04-19 06:36:26 +00:00
h . Write ( [ ] byte ( c . JSTokenBox . Load ( ) . ( string ) ) )
2018-10-16 10:02:51 +00:00
h . Write ( [ ] byte ( user . LastIP ) )
if r . PostFormValue ( "golden-watch" ) != hex . EncodeToString ( h . Sum ( nil ) ) {
2018-11-01 06:43:56 +00:00
regError ( phrases . GetErrorPhrase ( "register_might_be_machine" ) , "js-antispam" )
2018-10-16 10:02:51 +00:00
}
2018-05-31 06:51:31 +00:00
}
2019-04-19 06:36:26 +00:00
username := c . SanitiseSingleLine ( r . PostFormValue ( "username" ) )
2018-05-31 06:51:31 +00:00
// TODO: Add a dedicated function for validating emails
2019-04-19 06:36:26 +00:00
email := c . SanitiseSingleLine ( r . PostFormValue ( "email" ) )
2018-02-03 05:47:14 +00:00
if username == "" {
2018-11-01 06:43:56 +00:00
regError ( phrases . GetErrorPhrase ( "register_need_username" ) , "no-username" )
2018-02-03 05:47:14 +00:00
}
if email == "" {
2018-11-01 06:43:56 +00:00
regError ( phrases . GetErrorPhrase ( "register_need_email" ) , "no-email" )
2018-02-03 05:47:14 +00:00
}
2018-09-20 04:36:50 +00:00
// This is so a numeric name won't interfere with mentioning a user by ID, there might be a better way of doing this like perhaps !@ to mean IDs and @ to mean usernames in the pre-parser
usernameBits := strings . Split ( username , " " )
if isNumeric ( usernameBits [ 0 ] ) {
2018-11-01 06:43:56 +00:00
regError ( phrases . GetErrorPhrase ( "register_first_word_numeric" ) , "numeric-name" )
2018-09-20 04:36:50 +00:00
}
2019-04-19 06:36:26 +00:00
ok := c . HasSuspiciousEmail ( email )
2018-06-30 10:22:39 +00:00
if ok {
2018-11-01 06:43:56 +00:00
regError ( phrases . GetErrorPhrase ( "register_suspicious_email" ) , "suspicious-email" )
2018-06-30 10:22:39 +00:00
}
2018-02-03 05:47:14 +00:00
password := r . PostFormValue ( "password" )
// ? Move this into Create()? What if we want to programatically set weak passwords for tests?
2019-04-19 06:36:26 +00:00
err := c . WeakPassword ( password , username , email )
2018-02-03 05:47:14 +00:00
if err != nil {
2018-05-16 10:46:14 +00:00
regError ( err . Error ( ) , "weak-password" )
} else {
// Do the two inputted passwords match..?
confirmPassword := r . PostFormValue ( "confirm_password" )
if password != confirmPassword {
2018-11-01 06:43:56 +00:00
regError ( phrases . GetErrorPhrase ( "register_password_mismatch" ) , "password-mismatch" )
2018-05-16 10:46:14 +00:00
}
2018-02-03 05:47:14 +00:00
}
2019-04-19 06:36:26 +00:00
regLog := c . RegLogItem { Username : username , Email : email , FailureReason : regErrReason , Success : regSuccess , IPAddress : user . LastIP }
2018-05-16 10:46:14 +00:00
_ , err = regLog . Create ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-16 10:46:14 +00:00
}
if ! regSuccess {
2019-04-19 06:36:26 +00:00
return c . LocalError ( regErrMsg , w , r , user )
2018-02-03 05:47:14 +00:00
}
var active bool
var group int
switch headerLite . Settings [ "activation_type" ] {
case 1 : // Activate All
active = true
2019-04-19 06:36:26 +00:00
group = c . Config . DefaultGroup
2018-02-03 05:47:14 +00:00
default : // Anything else. E.g. Admin Activation or Email Activation.
2019-04-19 06:36:26 +00:00
group = c . Config . ActivationGroup
2018-02-03 05:47:14 +00:00
}
2018-05-16 10:46:14 +00:00
// TODO: Do the registration attempt logging a little less messily (without having to amend the result after the insert)
2019-04-19 06:36:26 +00:00
uid , err := c . Users . Create ( username , password , email , group , active )
2018-05-16 10:46:14 +00:00
if err != nil {
regLog . Success = false
2019-04-19 06:36:26 +00:00
if err == c . ErrAccountExists {
2018-05-16 10:46:14 +00:00
regLog . FailureReason += "username-exists"
err = regLog . Commit ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-16 10:46:14 +00:00
}
2019-04-19 06:36:26 +00:00
return c . LocalError ( phrases . GetErrorPhrase ( "register_username_unavailable" ) , w , r , user )
} else if err == c . ErrLongUsername {
2018-05-16 10:46:14 +00:00
regLog . FailureReason += "username-too-long"
err = regLog . Commit ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-16 10:46:14 +00:00
}
2019-04-19 06:36:26 +00:00
return c . LocalError ( phrases . GetErrorPhrase ( "register_username_too_long_prefix" ) + strconv . Itoa ( c . Config . MaxUsernameLength ) , w , r , user )
2018-05-16 10:46:14 +00:00
}
regLog . FailureReason += "internal-error"
err2 := regLog . Commit ( )
if err2 != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err2 , w , r )
2018-05-16 10:46:14 +00:00
}
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-02-03 05:47:14 +00:00
}
2019-04-19 06:36:26 +00:00
session , err := c . Auth . CreateSession ( uid )
2019-03-03 03:19:32 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-03 03:19:32 +00:00
}
2019-04-19 06:36:26 +00:00
c . Auth . SetCookies ( w , uid , session )
2019-03-03 03:19:32 +00:00
2018-02-03 05:47:14 +00:00
// Check if this user actually owns this email, if email activation is on, automatically flip their account to active when the email is validated. Validation is also useful for determining whether this user should receive any alerts, etc. via email
2019-04-19 06:36:26 +00:00
if c . Site . EnableEmails {
token , err := c . GenerateSafeString ( 80 )
2018-02-03 05:47:14 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-02-03 05:47:14 +00:00
}
// TODO: Add an EmailStore and move this there
2018-08-04 11:46:36 +00:00
_ , err = qgen . NewAcc ( ) . Insert ( "emails" ) . Columns ( "email, uid, validated, token" ) . Fields ( "?,?,?,?" ) . Exec ( email , uid , 0 , token )
2018-02-03 05:47:14 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-02-03 05:47:14 +00:00
}
2019-04-19 06:36:26 +00:00
err = c . SendValidationEmail ( username , email , token )
2019-03-03 03:19:32 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( phrases . GetErrorPhrase ( "register_email_fail" ) , w , r , user )
2018-02-03 05:47:14 +00:00
}
}
http . Redirect ( w , r , "/" , http . StatusSeeOther )
return nil
}
2018-06-17 07:28:18 +00:00
// TODO: Figure a way of making this into middleware?
2019-04-19 06:36:26 +00:00
func accountEditHead ( titlePhrase string , w http . ResponseWriter , r * http . Request , user * c . User , header * c . Header ) {
2018-11-01 06:43:56 +00:00
header . Title = phrases . GetTitlePhrase ( titlePhrase )
2018-10-14 05:08:44 +00:00
header . Path = "/user/edit/"
2018-06-17 07:28:18 +00:00
header . AddSheet ( header . Theme . Name + "/account.css" )
2019-03-24 07:23:38 +00:00
header . AddScriptAsync ( "account.js" )
2018-06-17 07:28:18 +00:00
}
2019-04-19 06:36:26 +00:00
func AccountEdit ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-11-12 09:23:36 +00:00
accountEditHead ( "account" , w , r , & user , header )
2018-06-17 07:28:18 +00:00
if r . FormValue ( "avatar_updated" ) == "1" {
header . AddNotice ( "account_avatar_updated" )
} else if r . FormValue ( "username_updated" ) == "1" {
header . AddNotice ( "account_username_updated" )
} else if r . FormValue ( "mfa_setup_success" ) == "1" {
header . AddNotice ( "account_mfa_setup_success" )
}
// TODO: Find a more efficient way of doing this
var mfaSetup = false
2019-04-19 06:36:26 +00:00
_ , err := c . MFAstore . Get ( user . ID )
2018-06-17 07:28:18 +00:00
if err != sql . ErrNoRows && err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
} else if err != sql . ErrNoRows {
mfaSetup = true
}
2018-10-08 05:34:25 +00:00
// Normalise the score so that the user sees their relative progress to the next level rather than showing them their total score
2019-04-19 06:36:26 +00:00
prevScore := c . GetLevelScore ( user . Level )
2018-10-08 05:34:25 +00:00
currentScore := user . Score - prevScore
2019-04-19 06:36:26 +00:00
nextScore := c . GetLevelScore ( user . Level + 1 ) - prevScore
2018-10-14 05:08:44 +00:00
perc := int ( math . Ceil ( ( float64 ( nextScore ) / float64 ( currentScore ) ) * 100 ) )
2018-10-08 05:34:25 +00:00
2019-04-19 06:36:26 +00:00
pi := c . Account { header , "dashboard" , "account_own_edit" , c . AccountDashPage { header , mfaSetup , currentScore , nextScore , user . Level + 1 , perc * 2 } }
2018-10-27 03:21:02 +00:00
return renderTemplate ( "account" , w , r , header , pi )
2018-06-17 07:28:18 +00:00
}
2018-11-01 06:43:56 +00:00
//edit_password
2019-04-19 06:36:26 +00:00
func AccountEditPassword ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-11-12 09:23:36 +00:00
accountEditHead ( "account_password" , w , r , & user , header )
2019-04-19 09:34:16 +00:00
return renderTemplate ( "account_own_edit_password" , w , r , header , c . Page { header , tList , nil } )
2018-01-23 10:48:44 +00:00
}
2018-05-14 08:56:56 +00:00
2018-06-17 07:28:18 +00:00
// TODO: Require re-authentication if the user hasn't logged in in a while
2019-04-19 06:36:26 +00:00
func AccountEditPasswordSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
_ , ferr := c . SimpleUserCheck ( w , r , & user )
2018-05-14 08:56:56 +00:00
if ferr != nil {
return ferr
}
var realPassword , salt string
currentPassword := r . PostFormValue ( "account-current-password" )
newPassword := r . PostFormValue ( "account-new-password" )
confirmPassword := r . PostFormValue ( "account-confirm-password" )
// TODO: Use a reusable statement
2018-08-04 11:46:36 +00:00
err := qgen . NewAcc ( ) . Select ( "users" ) . Columns ( "password, salt" ) . Where ( "uid = ?" ) . QueryRow ( user . ID ) . Scan ( & realPassword , & salt )
2018-05-14 08:56:56 +00:00
if err == sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Your account no longer exists." , w , r , user )
2018-05-14 08:56:56 +00:00
} else if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-14 08:56:56 +00:00
}
2019-04-19 06:36:26 +00:00
err = c . CheckPassword ( realPassword , currentPassword , salt )
if err == c . ErrMismatchedHashAndPassword {
return c . LocalError ( "That's not the correct password." , w , r , user )
2018-05-14 08:56:56 +00:00
} else if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-14 08:56:56 +00:00
}
if newPassword != confirmPassword {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "The two passwords don't match." , w , r , user )
2018-05-14 08:56:56 +00:00
}
2019-04-19 06:36:26 +00:00
c . SetPassword ( user . ID , newPassword ) // TODO: Limited version of WeakPassword()
2018-05-14 08:56:56 +00:00
// Log the user out as a safety precaution
2019-04-19 06:36:26 +00:00
c . Auth . ForceLogout ( user . ID )
2018-05-14 08:56:56 +00:00
http . Redirect ( w , r , "/" , http . StatusSeeOther )
return nil
}
2019-04-19 06:36:26 +00:00
func AccountEditAvatarSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
_ , ferr := c . SimpleUserCheck ( w , r , & user )
2018-05-14 08:56:56 +00:00
if ferr != nil {
return ferr
}
2019-06-09 03:21:48 +00:00
if ! user . Perms . UploadAvatars {
return c . NoPermissions ( w , r , user )
}
2018-05-14 08:56:56 +00:00
2018-07-28 12:52:23 +00:00
// We don't want multiple files
// TODO: Are we doing this correctly?
filenameMap := make ( map [ string ] bool )
for _ , fheaders := range r . MultipartForm . File {
for _ , hdr := range fheaders {
if hdr . Filename == "" {
continue
}
filenameMap [ hdr . Filename ] = true
}
}
if len ( filenameMap ) > 1 {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You may only upload one avatar" , w , r , user )
2018-07-28 12:52:23 +00:00
}
var ext string
2018-05-14 08:56:56 +00:00
for _ , fheaders := range r . MultipartForm . File {
for _ , hdr := range fheaders {
if hdr . Filename == "" {
continue
}
infile , err := hdr . Open ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Upload failed" , w , r , user )
2018-05-14 08:56:56 +00:00
}
defer infile . Close ( )
if ext == "" {
extarr := strings . Split ( hdr . Filename , "." )
if len ( extarr ) < 2 {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Bad file" , w , r , user )
2018-05-14 08:56:56 +00:00
}
ext = extarr [ len ( extarr ) - 1 ]
// TODO: Can we do this without a regex?
reg , err := regexp . Compile ( "[^A-Za-z0-9]+" )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Bad file extension" , w , r , user )
2018-05-14 08:56:56 +00:00
}
ext = reg . ReplaceAllString ( ext , "" )
ext = strings . ToLower ( ext )
2018-07-28 12:52:23 +00:00
2019-04-19 06:36:26 +00:00
if ! c . ImageFileExts . Contains ( ext ) {
return c . LocalError ( "You can only use an image for your avatar" , w , r , user )
2018-07-28 12:52:23 +00:00
}
2018-05-14 08:56:56 +00:00
}
2018-07-28 12:52:23 +00:00
// TODO: Centralise this string, so we don't have to change it in two different places when it changes
2018-05-14 08:56:56 +00:00
outfile , err := os . Create ( "./uploads/avatar_" + strconv . Itoa ( user . ID ) + "." + ext )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Upload failed [File Creation Failed]" , w , r , user )
2018-05-14 08:56:56 +00:00
}
defer outfile . Close ( )
_ , err = io . Copy ( outfile , infile )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Upload failed [Copy Failed]" , w , r , user )
2018-05-14 08:56:56 +00:00
}
}
}
if ext == "" {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "No file" , w , r , user )
2018-05-14 08:56:56 +00:00
}
err := user . ChangeAvatar ( "." + ext )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-14 08:56:56 +00:00
}
2019-03-05 04:46:43 +00:00
// Clean up the old avatar data, so we don't end up with too many dead files in /uploads/
if len ( user . RawAvatar ) > 2 {
if user . RawAvatar [ 0 ] == '.' && user . RawAvatar [ 1 ] == '.' {
err := os . Remove ( "./uploads/avatar_" + strconv . Itoa ( user . ID ) + "_tmp" + user . RawAvatar [ 1 : ] )
if err != nil && ! os . IsNotExist ( err ) {
2019-04-19 06:36:26 +00:00
c . LogWarning ( err )
return c . LocalError ( "Something went wrong" , w , r , user )
2019-03-05 04:46:43 +00:00
}
err = os . Remove ( "./uploads/avatar_" + strconv . Itoa ( user . ID ) + "_w48" + user . RawAvatar [ 1 : ] )
if err != nil && ! os . IsNotExist ( err ) {
2019-04-19 06:36:26 +00:00
c . LogWarning ( err )
return c . LocalError ( "Something went wrong" , w , r , user )
2019-03-05 04:46:43 +00:00
}
}
}
2018-07-28 12:52:23 +00:00
// TODO: Only schedule a resize if the avatar isn't tiny
err = user . ScheduleAvatarResize ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-07-28 12:52:23 +00:00
}
2018-06-17 07:28:18 +00:00
http . Redirect ( w , r , "/user/edit/?avatar_updated=1" , http . StatusSeeOther )
2018-05-14 08:56:56 +00:00
return nil
}
2019-06-09 03:21:48 +00:00
func AccountEditRevokeAvatarSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
_ , ferr := c . SimpleUserCheck ( w , r , & user )
if ferr != nil {
return ferr
}
err := user . ChangeAvatar ( "" )
if err != nil {
return c . InternalError ( err , w , r )
}
// Clean up the old avatar data, so we don't end up with too many dead files in /uploads/
if len ( user . RawAvatar ) > 2 {
if user . RawAvatar [ 0 ] == '.' && user . RawAvatar [ 1 ] == '.' {
err := os . Remove ( "./uploads/avatar_" + strconv . Itoa ( user . ID ) + "_tmp" + user . RawAvatar [ 1 : ] )
if err != nil && ! os . IsNotExist ( err ) {
c . LogWarning ( err )
return c . LocalError ( "Something went wrong" , w , r , user )
}
err = os . Remove ( "./uploads/avatar_" + strconv . Itoa ( user . ID ) + "_w48" + user . RawAvatar [ 1 : ] )
if err != nil && ! os . IsNotExist ( err ) {
c . LogWarning ( err )
return c . LocalError ( "Something went wrong" , w , r , user )
}
}
}
http . Redirect ( w , r , "/user/edit/?avatar_updated=1" , http . StatusSeeOther )
return nil
}
2019-04-19 06:36:26 +00:00
func AccountEditUsernameSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
_ , ferr := c . SimpleUserCheck ( w , r , & user )
2018-05-14 08:56:56 +00:00
if ferr != nil {
return ferr
}
2018-06-17 07:28:18 +00:00
2019-04-19 06:36:26 +00:00
newUsername := c . SanitiseSingleLine ( r . PostFormValue ( "account-new-username" ) )
2018-06-17 07:28:18 +00:00
if newUsername == "" {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You can't leave your username blank" , w , r , user )
2018-06-17 07:28:18 +00:00
}
err := user . ChangeName ( newUsername )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Unable to change the username. Does someone else already have this name?" , w , r , user )
2018-06-17 07:28:18 +00:00
}
http . Redirect ( w , r , "/user/edit/?username_updated=1" , http . StatusSeeOther )
return nil
}
2019-04-19 06:36:26 +00:00
func AccountEditMFA ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-11-12 09:23:36 +00:00
accountEditHead ( "account_mfa" , w , r , & user , header )
2018-06-17 07:28:18 +00:00
2019-04-19 06:36:26 +00:00
mfaItem , err := c . MFAstore . Get ( user . ID )
2018-06-17 07:28:18 +00:00
if err != sql . ErrNoRows && err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
} else if err == sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Two-factor authentication hasn't been setup on your account" , w , r , user )
2018-05-14 08:56:56 +00:00
}
2019-04-19 06:36:26 +00:00
pi := c . Page { header , tList , mfaItem . Scratch }
2018-12-17 04:58:55 +00:00
return renderTemplate ( "account_own_edit_mfa" , w , r , header , pi )
2018-05-14 08:56:56 +00:00
}
2018-06-17 07:28:18 +00:00
// If not setup, generate a string, otherwise give an option to disable mfa given the right code
2019-04-19 06:36:26 +00:00
func AccountEditMFASetup ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-11-12 09:23:36 +00:00
accountEditHead ( "account_mfa_setup" , w , r , & user , header )
2018-06-17 07:28:18 +00:00
// Flash an error if mfa is already setup
2019-04-19 06:36:26 +00:00
_ , err := c . MFAstore . Get ( user . ID )
2018-06-17 07:28:18 +00:00
if err != sql . ErrNoRows && err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
} else if err != sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You have already setup two-factor authentication" , w , r , user )
2018-06-17 07:28:18 +00:00
}
// TODO: Entitise this?
2019-04-19 06:36:26 +00:00
code , err := c . GenerateGAuthSecret ( )
2018-06-17 07:28:18 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
}
2019-04-19 06:36:26 +00:00
pi := c . Page { header , tList , c . FriendlyGAuthSecret ( code ) }
2018-12-17 04:58:55 +00:00
return renderTemplate ( "account_own_edit_mfa_setup" , w , r , header , pi )
2018-06-17 07:28:18 +00:00
}
// Form should bounce the random mfa secret back and the otp to be verified server-side to reduce the chances of a bug arising on the JS side which makes every code mismatch
2019-04-19 06:36:26 +00:00
func AccountEditMFASetupSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
_ , ferr := c . SimpleUserCheck ( w , r , & user )
2018-05-14 08:56:56 +00:00
if ferr != nil {
return ferr
}
2018-06-17 07:28:18 +00:00
// Flash an error if mfa is already setup
2019-04-19 06:36:26 +00:00
_ , err := c . MFAstore . Get ( user . ID )
2018-06-17 07:28:18 +00:00
if err != sql . ErrNoRows && err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
} else if err != sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You have already setup two-factor authentication" , w , r , user )
2018-06-17 07:28:18 +00:00
}
var code = r . PostFormValue ( "code" )
var otp = r . PostFormValue ( "otp" )
2019-04-19 06:36:26 +00:00
ok , err := c . VerifyGAuthToken ( code , otp )
2018-05-14 08:56:56 +00:00
if err != nil {
2018-06-17 07:28:18 +00:00
//fmt.Println("err: ", err)
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Something weird happened" , w , r , user ) // TODO: Log this error?
2018-06-17 07:28:18 +00:00
}
// TODO: Use AJAX for this
if ! ok {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "The token isn't right" , w , r , user )
2018-06-17 07:28:18 +00:00
}
// TODO: How should we handle races where a mfa key is already setup? Right now, it's a fairly generic error, maybe try parsing the error message?
2019-04-19 06:36:26 +00:00
err = c . MFAstore . Create ( code , user . ID )
2018-06-17 07:28:18 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-14 08:56:56 +00:00
}
2018-06-17 07:28:18 +00:00
http . Redirect ( w , r , "/user/edit/?mfa_setup_success=1" , http . StatusSeeOther )
2018-05-14 08:56:56 +00:00
return nil
}
2018-05-27 09:36:35 +00:00
2018-06-17 07:28:18 +00:00
// TODO: Implement this
2019-04-19 06:36:26 +00:00
func AccountEditMFADisableSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
_ , ferr := c . SimpleUserCheck ( w , r , & user )
2018-05-27 09:36:35 +00:00
if ferr != nil {
return ferr
}
2018-06-17 07:28:18 +00:00
// Flash an error if mfa is already setup
2019-04-19 06:36:26 +00:00
mfaItem , err := c . MFAstore . Get ( user . ID )
2018-06-17 07:28:18 +00:00
if err != sql . ErrNoRows && err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
} else if err == sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You don't have two-factor enabled on your account" , w , r , user )
2018-06-17 07:28:18 +00:00
}
err = mfaItem . Delete ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-06-17 07:28:18 +00:00
}
http . Redirect ( w , r , "/user/edit/?mfa_disabled=1" , http . StatusSeeOther )
return nil
}
2019-04-19 06:36:26 +00:00
func AccountEditEmail ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-11-12 09:23:36 +00:00
accountEditHead ( "account_email" , w , r , & user , header )
2019-04-19 06:36:26 +00:00
emails , err := c . Emails . GetEmailsByUser ( & user )
2018-05-27 09:36:35 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-27 09:36:35 +00:00
}
// Was this site migrated from another forum software? Most of them don't have multiple emails for a single user.
// This also applies when the admin switches site.EnableEmails on after having it off for a while.
if len ( emails ) == 0 {
2019-04-19 06:36:26 +00:00
email := c . Email { UserID : user . ID }
2018-05-27 09:36:35 +00:00
email . Email = user . Email
email . Validated = false
email . Primary = true
emails = append ( emails , email )
}
2019-04-19 06:36:26 +00:00
if ! c . Site . EnableEmails {
2018-06-06 00:29:12 +00:00
header . AddNotice ( "account_mail_disabled" )
2018-05-27 09:36:35 +00:00
}
if r . FormValue ( "verified" ) == "1" {
2018-06-06 00:29:12 +00:00
header . AddNotice ( "account_mail_verify_success" )
2018-05-27 09:36:35 +00:00
}
2019-04-19 06:36:26 +00:00
pi := c . Account { header , "edit_emails" , "account_own_edit_email" , c . EmailListPage { header , emails } }
2018-12-17 04:58:55 +00:00
return renderTemplate ( "account" , w , r , header , pi )
2018-05-27 09:36:35 +00:00
}
2018-06-06 00:21:22 +00:00
// TODO: Should we make this an AnonAction so someone can do this without being logged in?
2019-04-19 06:36:26 +00:00
func AccountEditEmailTokenSubmit ( w http . ResponseWriter , r * http . Request , user c . User , token string ) c . RouteError {
header , ferr := c . UserCheck ( w , r , & user )
2018-05-27 09:36:35 +00:00
if ferr != nil {
return ferr
}
2019-04-19 06:36:26 +00:00
if ! c . Site . EnableEmails {
2018-05-27 09:36:35 +00:00
http . Redirect ( w , r , "/user/edit/email/" , http . StatusSeeOther )
return nil
}
2019-04-19 06:36:26 +00:00
targetEmail := c . Email { UserID : user . ID }
emails , err := c . Emails . GetEmailsByUser ( & user )
2018-05-27 09:36:35 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You are not logged in" , w , r , user )
2018-05-27 09:36:35 +00:00
}
for _ , email := range emails {
2019-03-11 08:47:45 +00:00
if subtle . ConstantTimeCompare ( [ ] byte ( email . Token ) , [ ] byte ( token ) ) == 1 {
2018-05-27 09:36:35 +00:00
targetEmail = email
}
}
if len ( emails ) == 0 {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "A verification email was never sent for you!" , w , r , user )
2018-05-27 09:36:35 +00:00
}
if targetEmail . Token == "" {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "That's not a valid token!" , w , r , user )
2018-05-27 09:36:35 +00:00
}
2019-04-19 06:36:26 +00:00
err = c . Emails . VerifyEmail ( user . Email )
2018-05-27 09:36:35 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-27 09:36:35 +00:00
}
// If Email Activation is on, then activate the account while we're here
2018-06-06 00:21:22 +00:00
if header . Settings [ "activation_type" ] == 2 {
2018-05-27 09:36:35 +00:00
err = user . Activate ( )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-05-27 09:36:35 +00:00
}
}
http . Redirect ( w , r , "/user/edit/email/?verified=1" , http . StatusSeeOther )
return nil
}
2018-10-10 07:33:51 +00:00
2019-04-19 06:36:26 +00:00
func AccountLogins ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-12-17 04:58:55 +00:00
accountEditHead ( "account_logins" , w , r , & user , header )
2019-06-01 12:31:48 +00:00
logCount := c . LoginLogs . CountUser ( user . ID )
2018-12-17 04:58:55 +00:00
page , _ := strconv . Atoi ( r . FormValue ( "page" ) )
perPage := 12
2019-04-19 06:36:26 +00:00
offset , page , lastPage := c . PageOffset ( logCount , page , perPage )
2018-12-17 04:58:55 +00:00
2019-04-19 06:36:26 +00:00
logs , err := c . LoginLogs . GetOffset ( user . ID , offset , perPage )
2018-12-17 04:58:55 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2018-12-17 04:58:55 +00:00
}
2019-06-04 05:48:12 +00:00
pageList := c . Paginate ( page , lastPage , 5 )
2019-04-19 06:36:26 +00:00
pi := c . Account { header , "logins" , "account_logins" , c . AccountLoginsPage { header , logs , c . Paginator { pageList , page , lastPage } } }
2018-12-17 04:58:55 +00:00
return renderTemplate ( "account" , w , r , header , pi )
}
2019-04-19 06:36:26 +00:00
func LevelList ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2018-11-01 06:43:56 +00:00
header . Title = phrases . GetTitlePhrase ( "account_level_list" )
2018-10-10 07:33:51 +00:00
2019-04-19 06:36:26 +00:00
var fScores = c . GetLevels ( 20 )
var levels = make ( [ ] c . LevelListItem , len ( fScores ) )
2018-10-10 07:33:51 +00:00
for i , fScore := range fScores {
var status string
if user . Level > i {
status = "complete"
} else if user . Level < i {
status = "future"
} else {
status = "inprogress"
}
iScore := int ( math . Ceil ( fScore ) )
perc := int ( math . Ceil ( ( fScore / float64 ( user . Score ) ) * 100 ) )
2019-04-19 06:36:26 +00:00
levels [ i ] = c . LevelListItem { i , iScore , status , perc * 2 }
2018-10-10 07:33:51 +00:00
}
2019-04-19 09:34:16 +00:00
return renderTemplate ( "level_list" , w , r , header , c . LevelListPage { header , levels [ 1 : ] } )
2018-10-10 07:33:51 +00:00
}
2019-03-11 08:47:45 +00:00
2019-04-19 06:36:26 +00:00
func Alerts ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2019-03-11 08:47:45 +00:00
return nil
}
2019-04-19 06:36:26 +00:00
func AccountPasswordReset ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2019-03-11 08:47:45 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
if ! c . Site . EnableEmails {
return c . LocalError ( phrases . GetNoticePhrase ( "account_mail_disabled" ) , w , r , user )
2019-03-11 08:47:45 +00:00
}
if r . FormValue ( "email_sent" ) == "1" {
header . AddNotice ( "password_reset_email_sent" )
}
header . Title = phrases . GetTitlePhrase ( "password_reset" )
2019-04-19 06:36:26 +00:00
return renderTemplate ( "password_reset" , w , r , header , c . Page { header , tList , nil } )
2019-03-11 08:47:45 +00:00
}
// TODO: Ratelimit this
2019-04-19 06:36:26 +00:00
func AccountPasswordResetSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
2019-03-11 08:47:45 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
if ! c . Site . EnableEmails {
return c . LocalError ( phrases . GetNoticePhrase ( "account_mail_disabled" ) , w , r , user )
2019-03-11 08:47:45 +00:00
}
username := r . PostFormValue ( "username" )
2019-04-19 06:36:26 +00:00
tuser , err := c . Users . GetByName ( username )
2019-03-11 08:47:45 +00:00
if err == sql . ErrNoRows {
// Someone trying to stir up trouble?
http . Redirect ( w , r , "/accounts/password-reset/?email_sent=1" , http . StatusSeeOther )
return nil
} else if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
token , err := c . GenerateSafeString ( 80 )
2019-03-11 08:47:45 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
2019-03-12 09:13:57 +00:00
// TODO: Move these queries somewhere else
2019-03-11 08:47:45 +00:00
var disc string
err = qgen . NewAcc ( ) . Select ( "password_resets" ) . Columns ( "createdAt" ) . DateCutoff ( "createdAt" , 1 , "hour" ) . QueryRow ( ) . Scan ( & disc )
if err != nil && err != sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
if err == nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You can only send a password reset email for a user once an hour" , w , r , user )
2019-03-11 08:47:45 +00:00
}
2019-03-12 09:13:57 +00:00
count , err := qgen . NewAcc ( ) . Count ( "password_resets" ) . DateCutoff ( "createdAt" , 6 , "hour" ) . Total ( )
if err != nil && err != sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-12 09:13:57 +00:00
}
if count >= 3 {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You can only send a password reset email for a user three times every six hours" , w , r , user )
2019-03-12 09:13:57 +00:00
}
count , err = qgen . NewAcc ( ) . Count ( "password_resets" ) . DateCutoff ( "createdAt" , 12 , "hour" ) . Total ( )
if err != nil && err != sql . ErrNoRows {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-12 09:13:57 +00:00
}
if count >= 4 {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You can only send a password reset email for a user four times every twelve hours" , w , r , user )
2019-03-12 09:13:57 +00:00
}
2019-04-19 06:36:26 +00:00
err = c . PasswordResetter . Create ( tuser . Email , tuser . ID , token )
2019-03-11 08:47:45 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
var schema string
2019-04-19 06:36:26 +00:00
if c . Site . EnableSsl {
2019-03-11 08:47:45 +00:00
schema = "s"
}
2019-04-19 06:36:26 +00:00
err = c . SendEmail ( tuser . Email , phrases . GetTmplPhrase ( "password_reset_subject" ) , phrases . GetTmplPhrasef ( "password_reset_body" , tuser . Name , "http" + schema + "://" + c . Site . URL + "/accounts/password-reset/token/?uid=" + strconv . Itoa ( tuser . ID ) + "&token=" + token ) )
2019-03-11 08:47:45 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( phrases . GetErrorPhrase ( "password_reset_email_fail" ) , w , r , user )
2019-03-11 08:47:45 +00:00
}
http . Redirect ( w , r , "/accounts/password-reset/?email_sent=1" , http . StatusSeeOther )
return nil
}
2019-04-19 06:36:26 +00:00
func AccountPasswordResetToken ( w http . ResponseWriter , r * http . Request , user c . User , header * c . Header ) c . RouteError {
2019-03-11 08:47:45 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2019-03-11 08:47:45 +00:00
}
// TODO: Find a way to flash this notice
/ * if r . FormValue ( "token_verified" ) == "1" {
header . AddNotice ( "password_reset_token_token_verified" )
} * /
token := r . FormValue ( "token" )
uid , err := strconv . Atoi ( r . FormValue ( "uid" ) )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Invalid uid" , w , r , user )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
err = c . PasswordResetter . ValidateToken ( uid , token )
if err == sql . ErrNoRows || err == c . ErrBadResetToken {
return c . LocalError ( "This reset token has expired." , w , r , user )
2019-03-11 08:47:45 +00:00
} else if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
_ , err = c . MFAstore . Get ( uid )
2019-03-11 08:47:45 +00:00
if err != sql . ErrNoRows && err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
mfa := err != sql . ErrNoRows
header . Title = phrases . GetTitlePhrase ( "password_reset_token" )
2019-04-19 06:36:26 +00:00
return renderTemplate ( "password_reset_token" , w , r , header , c . ResetPage { header , uid , html . EscapeString ( token ) , mfa } )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
func AccountPasswordResetTokenSubmit ( w http . ResponseWriter , r * http . Request , user c . User ) c . RouteError {
2019-03-11 08:47:45 +00:00
if user . Loggedin {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "You're already logged in." , w , r , user )
2019-03-11 08:47:45 +00:00
}
token := r . FormValue ( "token" )
uid , err := strconv . Atoi ( r . FormValue ( "uid" ) )
if err != nil {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "Invalid uid" , w , r , user )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
if ! c . Users . Exists ( uid ) {
return c . LocalError ( "This reset token has expired." , w , r , user )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
err = c . PasswordResetter . ValidateToken ( uid , token )
if err == sql . ErrNoRows || err == c . ErrBadResetToken {
return c . LocalError ( "This reset token has expired." , w , r , user )
2019-03-11 08:47:45 +00:00
} else if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
mfaToken := r . PostFormValue ( "mfa_token" )
2019-04-19 06:36:26 +00:00
err = c . Auth . ValidateMFAToken ( mfaToken , uid )
if err != nil && err != c . ErrNoMFAToken {
return c . LocalError ( err . Error ( ) , w , r , user )
2019-03-11 08:47:45 +00:00
}
newPassword := r . PostFormValue ( "password" )
confirmPassword := r . PostFormValue ( "confirm_password" )
if newPassword != confirmPassword {
2019-04-19 06:36:26 +00:00
return c . LocalError ( "The two passwords don't match." , w , r , user )
2019-03-11 08:47:45 +00:00
}
2019-04-19 06:36:26 +00:00
c . SetPassword ( uid , newPassword ) // TODO: Limited version of WeakPassword()
2019-03-11 08:47:45 +00:00
2019-04-19 06:36:26 +00:00
err = c . PasswordResetter . FlushTokens ( uid )
2019-03-11 08:47:45 +00:00
if err != nil {
2019-04-19 06:36:26 +00:00
return c . InternalError ( err , w , r )
2019-03-11 08:47:45 +00:00
}
// Log the user out as a safety precaution
2019-04-19 06:36:26 +00:00
c . Auth . ForceLogout ( uid )
2019-03-11 08:47:45 +00:00
//http.Redirect(w, r, "/accounts/password-reset/token/?token_verified=1", http.StatusSeeOther)
http . Redirect ( w , r , "/" , http . StatusSeeOther )
return nil
}