Skip to content

Commit

Permalink
Start adding user settings
Browse files Browse the repository at this point in the history
  • Loading branch information
darcys22 committed Oct 25, 2021
1 parent 9893cc7 commit 7dc8f47
Show file tree
Hide file tree
Showing 8 changed files with 142 additions and 78 deletions.
50 changes: 25 additions & 25 deletions backend/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/gin-gonic/contrib/gzip"
"github.com/gin-gonic/gin"

"github.com/darcys22/godbledger-web/backend/middleware"
"github.com/darcys22/godbledger-web/backend/setting"

"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -46,42 +45,43 @@ func register(r *gin.Engine) {
// ---- Authenticated Views ---------

// Main/Journal Entry Page
r.GET("/", middleware.AuthorizeJWT(), Index)
r.GET("/api/journals", middleware.AuthorizeJWT(), GetJournals)
r.POST("/api/journals", middleware.AuthorizeJWT(), PostJournal)
r.GET("/api/journals/:id", middleware.AuthorizeJWT(), GetJournal)
r.POST("/api/journals/:id", middleware.AuthorizeJWT(), EditJournal)
r.DELETE("/api/journals/:id", middleware.AuthorizeJWT(), DeleteJournal)
r.GET("/", AuthorizeJWT(), Index)
r.GET("/api/journals", AuthorizeJWT(), GetJournals)
r.POST("/api/journals", AuthorizeJWT(), PostJournal)
r.GET("/api/journals/:id", AuthorizeJWT(), GetJournal)
r.POST("/api/journals/:id", AuthorizeJWT(), EditJournal)
r.DELETE("/api/journals/:id", AuthorizeJWT(), DeleteJournal)

// Chart of Accounts Page
r.GET("/accounts", middleware.AuthorizeJWT(), Accounts)
r.GET("/api/accounts", middleware.AuthorizeJWT(), GetAccounts)
r.POST("/api/accounts", middleware.AuthorizeJWT(), PostAccount)
r.GET("/api/accounts/:id", middleware.AuthorizeJWT(), GetAccount)
r.DELETE("/api/accounts/:id", middleware.AuthorizeJWT(), DeleteAccount)
r.POST("/api/accounttags", middleware.AuthorizeJWT(), PostAccountTag)
r.DELETE("/api/accounttags/:account/:tagid", middleware.AuthorizeJWT(), DeleteAccountTag)
r.GET("/accounts", AuthorizeJWT(), Accounts)
r.GET("/api/accounts", AuthorizeJWT(), GetAccounts)
r.POST("/api/accounts", AuthorizeJWT(), PostAccount)
r.GET("/api/accounts/:id", AuthorizeJWT(), GetAccount)
r.DELETE("/api/accounts/:id", AuthorizeJWT(), DeleteAccount)
r.POST("/api/accounttags", AuthorizeJWT(), PostAccountTag)
r.DELETE("/api/accounttags/:account/:tagid", AuthorizeJWT(), DeleteAccountTag)

// Reconciliation Page
r.GET("/reconcile", middleware.AuthorizeJWT(), Reconcile)
r.GET("/api/reconcile/listexternalaccounts", middleware.AuthorizeJWT(), GetExternalAccountListing)
r.POST("/api/reconcile/listunreconciledtransactions", middleware.AuthorizeJWT(), GetUnreconciledTransactions)
r.GET("/reconcile", AuthorizeJWT(), Reconcile)
r.GET("/api/reconcile/listexternalaccounts", AuthorizeJWT(), GetExternalAccountListing)
r.POST("/api/reconcile/listunreconciledtransactions", AuthorizeJWT(), GetUnreconciledTransactions)

// Reports Page
r.GET("/reports", middleware.AuthorizeJWT(), Reports)
r.POST("api/reports/", middleware.AuthorizeJWT(), ReportsResults)
r.GET("/reports", AuthorizeJWT(), Reports)
r.POST("api/reports/", AuthorizeJWT(), ReportsResults)

// Modules Page
r.GET("/modules", middleware.AuthorizeJWT(), Modules)
r.GET("/modules", AuthorizeJWT(), Modules)

// Users Page
r.GET("/user", middleware.AuthorizeJWT(), User)
r.POST("/changepassword", middleware.AuthorizeJWT(), ChangePassword)
r.POST("/defaultcurrency", middleware.AuthorizeJWT(), DefaultCurrency)
r.GET("/user", AuthorizeJWT(), User)
r.GET("/api/user/settings", AuthorizeJWT(), GetUserSettings)
r.POST("/api/user/changepassword", AuthorizeJWT(), ChangePassword)
r.POST("/api/user/defaultcurrency", AuthorizeJWT(), DefaultCurrency)

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

}

Expand Down
76 changes: 75 additions & 1 deletion backend/api/user.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,85 @@
package api

import (
"net/http"
"net/url"

"github.com/darcys22/godbledger-web/backend/auth"
m "github.com/darcys22/godbledger-web/backend/models"

"github.com/gin-gonic/gin"
"net/http"
"github.com/dgrijalva/jwt-go"

)

type UserSettings struct {
// Simply the username/email will be displayed in client
Name string `json:"name"`
// Admin or Regular user, will allow for hiding admin screens but server side will also check
Role string `json:"role"`
// Used for date parsing - https://sugarjs.com/docs/#/DateLocales
DateLocale string `json:"datelocale"`
// USD - will be used by client for all currency items
DefaultCurrency string `json:"defaultcurrency"`
}

func respondWithError(ctx *gin.Context, message interface{}) {
log.Debugf("Error processing JWT: %v", message)
ctx.Abort()
location := url.URL{Path: "/login"}
ctx.Redirect(http.StatusFound, location.RequestURI())
}

func AuthorizeJWT() gin.HandlerFunc {
return func(ctx *gin.Context) {
cookie, err := ctx.Request.Cookie("access_token")
if err != nil {
respondWithError(ctx, "Cookie required")
return
}
tokenString := cookie.Value
token, err := auth.JWTAuthService().ValidateToken(tokenString)
if err != nil {
respondWithError(ctx, err)
return
} else {
if token.Valid {
claims := token.Claims.(jwt.MapClaims)
log.Println(claims)
} else {
respondWithError(ctx, "Invalid API token")
return
}
}
ctx.Next()
}
}

func GetUserSettings(ctx *gin.Context) {
settings := UserSettings{}
cookie, err := ctx.Request.Cookie("access_token")
if err != nil {
respondWithError(ctx, "Cookie required")
return
}
tokenString := cookie.Value
user, err := auth.JWTAuthService().ParseUser(tokenString)
if err != nil {
respondWithError(ctx, "Invalid API token")
return
} else {
settings.Name = user
//TODO sean put actual currency here
settings.DefaultCurrency = "USD"
//TODO sean put actual currency here
settings.DateLocale = "en-AU"
//settings.DateLocale = "en-US"
//TODO sean put actual role here
settings.Role = "Admin"
}
ctx.JSON(200, settings)
}

func ChangePassword(c *gin.Context) {
var journal m.PostJournalCommand

Expand Down
22 changes: 21 additions & 1 deletion backend/auth/LoginService.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func (info *loginInformation) NewUser(email string, password string) bool {
type JWTService interface {
GenerateToken(email string, isUser bool) string
ValidateToken(token string) (*jwt.Token, error)
ParseUser(token string) (string, error)
}
type authCustomClaims struct {
Name string `json:"name"`
Expand Down Expand Up @@ -89,10 +90,29 @@ func (service *jwtServices) GenerateToken(email string, isUser bool) string {
func (service *jwtServices) ValidateToken(encodedToken string) (*jwt.Token, error) {
return jwt.Parse(encodedToken, func(token *jwt.Token) (interface{}, error) {
if _, isvalid := token.Method.(*jwt.SigningMethodHMAC); !isvalid {
return nil, fmt.Errorf("Invalid token", token.Header["alg"])
return nil, fmt.Errorf("Invalid token %v", token.Header["alg"])

}
return []byte(service.secretKey), nil
})

}

//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 {
return nil, fmt.Errorf("Invalid token %v", token.Header["alg"])

}
return []byte(service.secretKey), nil
})
if err != nil {
return "", err
}
if claims, ok := token.Claims.(*authCustomClaims); ok && token.Valid {
return claims.Name, nil
} else {
return "", fmt.Errorf("Invalid Token")
}
}
47 changes: 0 additions & 47 deletions backend/middleware/JWTMiddleware.go

This file was deleted.

4 changes: 1 addition & 3 deletions public/app/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ class LineItem {
constructor() {
this._date = moment().format();
this._description = "";
//TODO sean this needs to be editable
this._currency= "USD";
this._currency= window.user.defaultcurrency;
this._account = "";
this._amount = 0;
}
Expand Down Expand Up @@ -632,7 +631,6 @@ const copyToClipboard = str => {
};

function main() {
Date.setLocale("en-AU");
$('#addJournal')[0].reset();
updateTotal()
$('#saveJournalButton').prop('disabled', true);
Expand Down
1 change: 0 additions & 1 deletion public/app/reports.js
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,5 @@ function dateQuickSelect(rangeType) {
}

function main() {
Date.setLocale("en-AU");
}
main();
19 changes: 19 additions & 0 deletions public/app/sidebar.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ let sidebar = document.querySelector(".sidebar");
let closeBtn = document.querySelector("#btn");
let searchBtn = document.querySelector(".bx-search");


closeBtn.addEventListener("click", ()=>{
sidebar.classList.toggle("open");
menuBtnChange();//calling the function(optional)
Expand All @@ -21,3 +22,21 @@ function menuBtnChange() {
}
}

fetch('/api/user/settings', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
.then(response => response.json())
.then(data => {
let name = document.querySelector(".name");
let role = document.querySelector(".job");
window.user = data
name.innerText = data.name
role.innerText = data.role
if (typeof Date.setLocale !== 'undefined') {
Date.setLocale(data.datelocale);
}
})

1 change: 1 addition & 0 deletions public/views/user.html
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ <h5 class="card-title">Default Date Locale</h5>
console.log("lol fail")
});
});

</script>
<!--Embed the footer.html template at this location-->
{{ template "footer.html" .}}

0 comments on commit 7dc8f47

Please sign in to comment.