Skip to content

Commit

Permalink
added transmission key to crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
yakuter committed Jul 21, 2020
1 parent c97f4f8 commit ac2def4
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 22 deletions.
3 changes: 2 additions & 1 deletion internal/api/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,8 @@ func RefreshToken(s storage.Store) http.HandlerFunc {
uuid := claims["uuid"].(string)

//Check from tokens db table
if !s.Tokens().Any(uuid) {
_, tokenExist := s.Tokens().Any(uuid)
if !tokenExist {
userid := claims["user_id"].(float64)
s.Tokens().Delete(int(userid))
RespondWithError(w, http.StatusUnauthorized, InvalidToken)
Expand Down
17 changes: 15 additions & 2 deletions internal/api/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,28 @@ func FindLoginsByID(s storage.Store) http.HandlerFunc {
// Create ...
func CreateLogin(s storage.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var loginDTO model.LoginDTO
type Payload struct {
Data string `json:"data"`
}
var payload Payload

decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&loginDTO); err != nil {
if err := decoder.Decode(&payload); err != nil {
RespondWithError(w, http.StatusBadRequest, InvalidRequestPayload)
return
}
defer r.Body.Close()

var loginDTO model.LoginDTO

key := r.Context().Value("transmissionKey").(string)
err := app.DecryptJSON(key, []byte(payload.Data), &loginDTO)
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}

fmt.Println(loginDTO)
schema := r.Context().Value("schema").(string)
createdLogin, err := app.CreateLogin(s, &loginDTO, schema)
if err != nil {
Expand Down
18 changes: 7 additions & 11 deletions internal/app/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,18 @@ package app

import (
"encoding/json"
"log"

openssl "github.com/Luzifer/go-openssl/v4"
"github.com/spf13/viper"
)

// DecryptJSON ...
func DecryptJSON(encrypted []byte, v interface{}) error {
func DecryptJSON(key string, encrypted []byte, v interface{}) error {

// 1. Get a openssl object and secret key from configs
// 1. Get a openssl object
o := openssl.New()
secret := viper.GetString("server.aesKey")

// 2. Decrypt string
dec, err := o.DecryptBytes(secret, encrypted, openssl.BytesToKeyMD5)
dec, err := o.DecryptBytes(key, encrypted, openssl.BytesToKeyMD5)
if err != nil {
return err
}
Expand All @@ -30,11 +27,10 @@ func DecryptJSON(encrypted []byte, v interface{}) error {
}

// EncryptJSON ...
func EncryptJSON(v interface{}) ([]byte, error) {
func EncryptJSON(key string, v interface{}) ([]byte, error) {

// 1. Get a openssl object and secret key from configs
// 1. Get a openssl object
o := openssl.New()
secret := viper.GetString("server.aesKey")

// 2. Marshall to text
text, err := json.Marshal(v)
Expand All @@ -43,10 +39,10 @@ func EncryptJSON(v interface{}) ([]byte, error) {
}

// 3. Encrypt it
enc, err := o.EncryptBytes(secret, text, openssl.BytesToKeyMD5)
enc, err := o.EncryptBytes(key, text, openssl.BytesToKeyMD5)
if err != nil {
return nil, err
}
log.Println(string(enc))

return enc, nil
}
8 changes: 6 additions & 2 deletions internal/router/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ func Auth(s storage.Store) negroni.HandlerFunc {
uuid, _ := claims["uuid"].(string)

//check from db
if !s.Tokens().Any(uuid) {
tokenRow, tokenExist := s.Tokens().Any(uuid)

if !tokenExist {
userid, _ := strconv.Atoi(fmt.Sprintf("%.f", claims["user_id"]))
s.Tokens().Delete(userid)
w.WriteHeader(http.StatusUnauthorized)
Expand All @@ -52,16 +54,18 @@ func Auth(s storage.Store) negroni.HandlerFunc {
ctxAuthorized := claims["authorized"].(bool)
ctxUserID := claims["user_id"].(float64)
ctxSchema := fmt.Sprintf("user%v", claims["user_id"])
ctxTransmissionKey := tokenRow.TransmissionKey

ctx := r.Context()
ctxWithID := context.WithValue(ctx, "id", ctxUserID)
ctxWithAuthorized := context.WithValue(ctxWithID, "authorized", ctxAuthorized)
ctxWithSchema := context.WithValue(ctxWithAuthorized, "schema", ctxSchema)
ctxWithTransmissionKey := context.WithValue(ctxWithSchema, "transmissionKey", ctxTransmissionKey)

// These context variables can be accesable with
// ctxAuthorized := r.Context().Value("authorized").(bool)
// ctxID := r.Context().Value("id").(float64)

next(w, r.WithContext(ctxWithSchema))
next(w, r.WithContext(ctxWithTransmissionKey))
})
}
2 changes: 1 addition & 1 deletion internal/storage/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ type EmailRepository interface {
// TokenRepository ...
// TODO: Add explanation to functions in TokenRepository
type TokenRepository interface {
Any(uuid string) bool
Any(uuid string) (model.Token, bool)
Save(userid int, uuid uuid.UUID, tkn string, expriydate time.Time, transmissionKey string)
Delete(userid int)
DeleteByUUID(uuid string)
Expand Down
9 changes: 4 additions & 5 deletions internal/storage/token/token_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,15 @@ func NewRepository(db *gorm.DB) *Repository {
return &Repository{db: db}
}

func (p *Repository) Any(uuid string) bool {
func (p *Repository) Any(uuid string) (model.Token, bool) {

var token model.Token
token := model.Token{}

if !p.db.Where("uuid = ?", uuid).First(&token).RecordNotFound() {
return true
return token, true
}

return false

return token, false
}

func (p *Repository) Save(userid int, uid uuid.UUID, tkn string, expriydate time.Time, transmissionKey string) {
Expand Down

0 comments on commit ac2def4

Please sign in to comment.