Skip to content

Commit

Permalink
update password, start add new user
Browse files Browse the repository at this point in the history
  • Loading branch information
darcys22 committed Nov 11, 2021
1 parent ec2ebf3 commit abba6e8
Show file tree
Hide file tree
Showing 12 changed files with 151 additions and 60 deletions.
8 changes: 4 additions & 4 deletions backend/api/accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func GetAccounts(c *gin.Context) {
log.Errorf("Could not get journal listing (%v)", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
c.JSON(200, accountsModel)
c.JSON(http.StatusOK, accountsModel)
}

func PostAccount(c *gin.Context) {
Expand All @@ -34,7 +34,7 @@ func PostAccount(c *gin.Context) {
if err := account.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
c.JSON(200, account)
c.JSON(http.StatusOK, account)
}

func DeleteAccount(c *gin.Context) {
Expand All @@ -54,7 +54,7 @@ func GetAccount(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}

c.JSON(200, account)
c.JSON(http.StatusOK, account)
}

func PostAccountTag(c *gin.Context) {
Expand All @@ -68,7 +68,7 @@ func PostAccountTag(c *gin.Context) {
//if err := account_tag.Save(); err != nil {
//c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
//}
//c.JSON(200, account_tag)
//c.JSON(http.StatusOK, account_tag)
}

func DeleteAccountTag(c *gin.Context) {
Expand Down
35 changes: 29 additions & 6 deletions backend/api/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,38 @@ import (
)

func NewUser(c *gin.Context) {
var journal m.PostJournalCommand
var new_user m.PostNewUserCommand

if err := c.BindJSON(&journal); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
if err := ctx.BindJSON(&new_user); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

if err := journal.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
cookie, err := ctx.Request.Cookie("access_token")
if err != nil {
respondWithError(ctx, "Cookie required")
return
}
tokenString := cookie.Value
username, err := auth.JWTAuthService().ParseUser(tokenString)
if err != nil {
respondWithError(ctx, "Invalid API token")
return
}

current_user, err := users.Get(username)
if err != nil {
respondWithError(ctx, "Could not find user")
return
}

if current_user.Role != "admin" {
respondWithError(ctx, "Unauthorised")
return
}

if err := users.Insert(new_user.Username, new_user.Email, new_user.Password); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
c.JSON(200, journal)
ctx.JSON(http.StatusOK, gin.H{"status": "success"})
}
2 changes: 1 addition & 1 deletion backend/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func register(r *gin.Engine) {

// Admin Page
r.GET("/admin", AuthorizeJWT(), Admin)
r.POST("/api/newuser", AuthorizeJWT(), NewUser)
r.POST("/api/admin/newuser", AuthorizeJWT(), NewUser)

}

Expand Down
8 changes: 4 additions & 4 deletions backend/api/journal.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func GetJournals(c *gin.Context) {
log.Errorf("Could not get journal listing (%v)", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
c.JSON(200, journalsModel)
c.JSON(http.StatusOK, journalsModel)
}

func PostJournal(c *gin.Context) {
Expand All @@ -27,7 +27,7 @@ func PostJournal(c *gin.Context) {
if err := journal.Save(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
c.JSON(200, journal)
c.JSON(http.StatusOK, journal)
}

func DeleteJournal(c *gin.Context) {
Expand All @@ -47,7 +47,7 @@ func GetJournal(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}

c.JSON(200, journal)
c.JSON(http.StatusOK, journal)
}

func EditJournal(c *gin.Context) {
Expand All @@ -67,5 +67,5 @@ func EditJournal(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}

c.JSON(200, journal)
c.JSON(http.StatusOK, journal)
}
2 changes: 1 addition & 1 deletion backend/api/reconcile.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ func GetUnreconciledTransactions(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}

c.JSON(200, unreconciledTransactionsResult)
c.JSON(http.StatusOK, unreconciledTransactionsResult)
}
2 changes: 1 addition & 1 deletion backend/api/reports.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ func ReportsResults(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}

c.JSON(200, reportResult)
c.JSON(http.StatusOK, reportResult)
}
43 changes: 36 additions & 7 deletions backend/api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,50 @@ func GetUserSettings(ctx *gin.Context) {
return
}

ctx.JSON(200, current_user.Settings())
ctx.JSON(http.StatusOK, current_user.Settings())
}

func ChangePassword(ctx *gin.Context) {
var journal m.PostJournalCommand
var password_change m.PostPasswordChangeCommand

if err := ctx.BindJSON(&journal); err != nil {
if err := ctx.BindJSON(&password_change); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

if err := journal.Save(); err != nil {
if password_change.NewPassword != password_change.ConfirmNewPassword {
respondWithError(ctx, "Confirmed Password does not match")
return
}

cookie, err := ctx.Request.Cookie("access_token")
if err != nil {
respondWithError(ctx, "Cookie required")
return
}
tokenString := cookie.Value
username, err := auth.JWTAuthService().ParseUser(tokenString)
if err != nil {
respondWithError(ctx, "Invalid API token")
return
}

current_user, err := users.Get(username)
if err != nil {
respondWithError(ctx, "Could not find user")
return
}

_, err = users.Authenticate(current_user.Email, password_change.Password)
if err != nil {
respondWithError(ctx, "Invalid Password")
return
}

if err := users.ChangePassword(current_user, password_change.NewPassword); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
ctx.JSON(200, journal)
ctx.JSON(http.StatusOK, gin.H{"status": "success"})
}

func DefaultCurrency(ctx *gin.Context) {
Expand Down Expand Up @@ -116,7 +145,7 @@ func DefaultCurrency(ctx *gin.Context) {
if err := users.Save(current_user); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
ctx.JSON(200, currency)
ctx.JSON(http.StatusOK, currency)
}

func DefaultLocale(ctx *gin.Context) {
Expand Down Expand Up @@ -150,5 +179,5 @@ func DefaultLocale(ctx *gin.Context) {
if err := users.Save(current_user); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
ctx.JSON(200, locale)
ctx.JSON(http.StatusOK, locale)
}
1 change: 0 additions & 1 deletion backend/auth/LoginService.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@ func (service *jwtServices) ValidateToken(encodedToken string) (*jwt.Token, erro

}

//type authCustomClaims struct {
func (service *jwtServices) ParseUser(encodedToken string) (string, error) {
token, err := jwt.ParseWithClaims(encodedToken, &authCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, isvalid := token.Method.(*jwt.SigningMethodHMAC); !isvalid {
Expand Down
15 changes: 15 additions & 0 deletions backend/models/sqlite/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,18 @@ func (m *UserModel) Save(user *models.User) (error) {
}
return nil
}

func (m *UserModel) ChangePassword(user *models.User, password string) (error) {
// Create a bcrypt hash of the plain-text password.
log.Infof("Updating user password, Name: %s Email: %s", user.Name , user.Email)
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 12)
if err != nil {
return err
}
stmt := `UPDATE users SET hashed_password = ? WHERE email = ? AND active = TRUE`
_, err = m.DB.Exec(stmt, hashedPassword, user.Email)
if err != nil {
return err
}
return nil
}
12 changes: 12 additions & 0 deletions backend/models/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ type PostLocaleCommand struct {
Locale string `json:"locale" binding:"required"`
}

type PostPasswordChangeCommand struct {
Password string `json:"password" binding:"required"`
NewPassword string `json:"new_password" binding:"required"`
ConfirmNewPassword string `json:"confirm_new_password" binding:"required"`
}

type PostNewUserCommand struct {
Username string `json:"username" binding:"required"`
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}

type UserSettingsResponse struct {
// Simply the username/email will be displayed in client
Name string `json:"name"`
Expand Down
46 changes: 28 additions & 18 deletions public/views/admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@ <h3 class="border-bottom border-gray pb-2 mb-0">Admin Page</h2>
<div class="card-body">
<h5 class="card-title">Create New User</h5>
<div>
<form class="validate-form" action="/newuser" method="post" id="changepassform">
<form class="validate-form" action="/api/admin/newuser" method="post" id="newuserform">
<div class="input-group flex-nowrap m-1">
<div class="input-group-prepend">
<span class="input-group-text lnr lnr-user"></span>
</div>
<input type="text" class="form-control" name="username", placeholder="Username" aria-label="Username" aria-describedby="addon-wrapping">
</div>
<div class="input-group flex-nowrap m-1">
<div class="input-group-prepend">
<span class="input-group-text lnr lnr-envelope"></span>
</div>
<input type="text" class="form-control" placeholder="Email" aria-label="Username" aria-describedby="addon-wrapping">
<input type="text" class="form-control" name="email", placeholder="Email" aria-label="Email" aria-describedby="addon-wrapping">
</div>
<div class="input-group flex-nowrap m-1">
<div class="input-group-prepend">
Expand All @@ -40,23 +46,27 @@ <h5 class="card-title">Create New User</h5>

<script>

$( "#changepassform" ).submit(function( event ) {
event.preventDefault();

var $form = $(this),
$("newuserform").submit(function( event ) {
event.preventDefault();
var $form = $(this)
url = $form.attr('action');

var posting = $.post(url, {
email: $('input[name = email]').val(),
password: $('input[name = password]').val()
});

posting.done(function(data) {
window.location.replace("/");
});
posting.fail(function() {
console.log("lol fail")
});
fetch(url,{
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
username: $('input[name = username]').val(),
email: $('input[name = email]').val(),
password: $('input[name = password]').val(),
})
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error))
});

</script>
Expand Down
37 changes: 20 additions & 17 deletions public/views/user.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,24 @@ <h2 class="border-bottom border-gray pb-2 mb-0">User Page</h2>
<div class="card-body">
<h5 class="card-title">Change Password</h5>
<div>
<form class="validate-form" action="/changepassword" method="post" id="changepassform">
<form class="validate-form" action="/api/user/changepassword" method="post" id="changepassform">
<div class="input-group flex-nowrap m-1">
<div class="input-group-prepend">
<span class="input-group-text lnr lnr-lock"></span>
</div>
<input type="password" class="form-control" name="previouspassword" placeholder="Previous Password" style="" autocomplete="off">
<input type="password" class="form-control" name="password" placeholder="Previous Password" style="" autocomplete="off">
</div>
<div class="input-group flex-nowrap m-1">
<div class="input-group-prepend">
<span class="input-group-text lnr lnr-lock"></span>
</div>
<input type="password" class="form-control" name="newpassword" placeholder="New Password" style="" autocomplete="off">
<input type="password" class="form-control" name="new_password" placeholder="New Password" style="" autocomplete="off">
</div>
<div class="input-group flex-nowrap m-1">
<div class="input-group-prepend">
<span class="input-group-text lnr lnr-lock"></span>
</div>
<input type="password" class="form-control" name="repeatpassword" placeholder="Repeat Password" style="" autocomplete="off">
<input type="password" class="form-control" name="confirm_new_password" placeholder="Repeat Password" style="" autocomplete="off">
</div>
<div>
<button type="submit" class="btn btn-primary m-1">Create User</button>
Expand Down Expand Up @@ -78,19 +78,22 @@ <h5 class="card-title">Default Date Locale</h5>

var $form = $(this)
url = $form.attr('action');

var posting = $.post(url, {
password: $('input[name = password]').val(),
newpassword: $('input[name = new_password]').val(),
confirmpassword: $('input[name = confirm_new_password]').val(),
});

posting.done(function(data) {
window.location.replace("/");
});
posting.fail(function() {
console.log("lol fail")
});
fetch(url,{
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
password: $('input[name = password]').val(),
new_password: $('input[name = new_password]').val(),
confirm_new_password: $('input[name = confirm_new_password]').val(),
})
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error(error))
});

$( "#changedefaultcurrency" ).submit(function( event ) {
Expand Down

0 comments on commit abba6e8

Please sign in to comment.