Skip to content

Commit

Permalink
add secret to user model
Browse files Browse the repository at this point in the history
  • Loading branch information
yakuter committed Jun 13, 2020
1 parent 6a51522 commit 84025c5
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 4 deletions.
4 changes: 2 additions & 2 deletions internal/api/auth.go
Expand Up @@ -134,7 +134,7 @@ func Signin(s storage.Store) http.HandlerFunc {
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
SecureKey: token.SecureKey,
UserDTOTable: model.ToUserDTOTable(*user),
UserDTO: model.ToUserDTO(user),
}

RespondWithJSON(w, 200, authLoginResponse)
Expand Down Expand Up @@ -204,7 +204,7 @@ func RefreshToken(s storage.Store) http.HandlerFunc {
AccessToken: newtoken.AccessToken,
RefreshToken: newtoken.RefreshToken,
SecureKey: newtoken.SecureKey,
UserDTOTable: model.ToUserDTOTable(*user),
UserDTO: model.ToUserDTO(user),
}

RespondWithJSON(w, 200, authLoginResponse)
Expand Down
25 changes: 25 additions & 0 deletions internal/api/system.go
Expand Up @@ -24,6 +24,31 @@ const (
BackupSuccess = "Backup completed successfully!"
)

// GeneratePassword generates new password
func CheckUpdate(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
product := vars["product"]

if product != "1" {
RespondWithError(w, http.StatusNotFound, "Product not found")
return
}

type Update struct {
LatestVersion string `json:"latest_version"`
DownloadUrl string `json:"download_url"`
ProductUrl string `json:"product_url"`
}

update := Update{
LatestVersion: "0.1.1",
DownloadUrl: "https://passwall.io/download/passwall-macos/",
ProductUrl: "https://signup.passwall.io",
}

RespondWithJSON(w, http.StatusOK, update)
}

// Languages ...
func Languages(s storage.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
Expand Down
52 changes: 52 additions & 0 deletions internal/app/encryption.go
Expand Up @@ -7,6 +7,8 @@ import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
mathRand "math/rand"
Expand Down Expand Up @@ -104,6 +106,56 @@ func Decrypt(dataStr string, passphrase string) []byte {
// return string(plainByte[:])
}

// Decrypt decrypts cipher text string into plain text string
func DecryptCBC(encrypted string) (string, error) {
key := []byte("1234123412341234")
cipherText := []byte(encrypted)

fmt.Println(len(cipherText))

block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}

if len(cipherText) < aes.BlockSize {
panic("cipherText too short")
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
if len(cipherText)%aes.BlockSize != 0 {
panic("cipherText is not a multiple of the block size")
}

mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(cipherText, cipherText)

cipherText, _ = Unpad(cipherText, aes.BlockSize)
return fmt.Sprintf("%s", cipherText), nil
}

func Pad(buf []byte, size int) ([]byte, error) {
bufLen := len(buf)
padLen := size - bufLen%size
padded := make([]byte, bufLen+padLen)
copy(padded, buf)
for i := 0; i < padLen; i++ {
padded[bufLen+i] = byte(padLen)
}
return padded, nil
}

func Unpad(padded []byte, size int) ([]byte, error) {
if len(padded)%size != 0 {
return nil, errors.New("pkcs7: Padded value wasn't in correct size.")
}

bufLen := len(padded) - int(padded[len(padded)-1])
buf := make([]byte, bufLen)
copy(buf, padded[:bufLen])
return buf, nil
}

// EncryptFile ...
func EncryptFile(filename string, data []byte, passphrase string) {
f, _ := os.Create(filename)
Expand Down
5 changes: 4 additions & 1 deletion internal/app/user.go
Expand Up @@ -11,9 +11,12 @@ import (
// CreateUser creates a user and saves it to the store
func CreateUser(s storage.Store, userDTO *model.UserDTO) (*model.User, error) {

// Hasing the master password with SHA256
// Hasing the master password with Bcrypt
userDTO.MasterPassword = NewBcrypt([]byte(userDTO.MasterPassword))

// Generate secret to use as salt
userDTO.Secret = GenerateSecureKey(16)

// New user's plan is Free and role is Member (not Admin)
userDTO.Plan = "Free"
userDTO.Role = "Member"
Expand Down
10 changes: 10 additions & 0 deletions internal/router/router.go
Expand Up @@ -97,10 +97,19 @@ func (r *Router) initRoutes() {
authRouter.HandleFunc("/refresh", api.RefreshToken(r.store)).Methods(http.MethodPost)
authRouter.HandleFunc("/check", api.CheckToken(r.store)).Methods(http.MethodPost)

// Check Updated
webRouter := mux.NewRouter().PathPrefix("/web").Subrouter()
webRouter.HandleFunc("/check-update/{product:[0-9]+}", api.CheckUpdate).Methods(http.MethodGet)

n := negroni.Classic()
n.Use(negroni.HandlerFunc(CORS))
n.Use(negroni.HandlerFunc(Secure))

r.router.PathPrefix("/web").Handler(n.With(
LimitHandler(),
negroni.Wrap(webRouter),
))

r.router.PathPrefix("/api").Handler(n.With(
Auth(r.store),
negroni.Wrap(apiRouter),
Expand All @@ -113,5 +122,6 @@ func (r *Router) initRoutes() {

// Insecure endpoints
r.router.HandleFunc("/health", api.HealthCheck(r.store)).Methods(http.MethodGet)
// r.router.HandleFunc("/check-update/{product:[0-9]+}", api.CheckUpdate).Methods(http.MethodGet)

}
2 changes: 1 addition & 1 deletion model/auth.go
Expand Up @@ -17,7 +17,7 @@ type AuthLoginResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
SecureKey string `json:"secure_key"`
UserDTOTable
*UserDTO
}

//TokenDetailsDTO ...
Expand Down
4 changes: 4 additions & 0 deletions model/user.go
Expand Up @@ -16,6 +16,7 @@ type User struct {
Name string `json:"name"`
Email string `json:"email"`
MasterPassword string `json:"master_password"`
Secret string `json:"secret"`
Plan string `json:"plan"`
Schema string `json:"schema"`
Role string `json:"role"`
Expand All @@ -27,6 +28,7 @@ type UserDTO struct {
Name string `json:"name" validate:"max=100"`
Email string `json:"email" validate:"required,email"`
MasterPassword string `json:"master_password" validate:"required,max=100,min=6"`
Secret string `json:"secret"`
Plan string `json:"plan"`
Schema string `json:"schema"`
Role string `json:"role"`
Expand All @@ -50,6 +52,7 @@ func ToUser(userDTO *UserDTO) *User {
Name: userDTO.Name,
Email: userDTO.Email,
MasterPassword: userDTO.MasterPassword,
Secret: userDTO.Secret,
Plan: userDTO.Plan,
Schema: userDTO.Schema,
Role: userDTO.Role,
Expand All @@ -64,6 +67,7 @@ func ToUserDTO(user *User) *UserDTO {
Name: user.Name,
Email: user.Email,
MasterPassword: user.MasterPassword,
Secret: user.Secret,
Plan: user.Plan,
Schema: user.Schema,
Role: user.Role,
Expand Down

0 comments on commit 84025c5

Please sign in to comment.