Inital commit

This commit is contained in:
2022-02-24 01:07:09 +13:00
commit 8bc3cee328
55 changed files with 2292 additions and 0 deletions

55
misc/helpers/helpers.go Normal file
View File

@@ -0,0 +1,55 @@
package helpers
import (
"crypto/rand"
"encoding/hex"
"log"
"path/filepath"
"runtime"
"golang.org/x/crypto/bcrypt"
)
//CheckError checks for errors and logs them and stops the program
func CheckError(err error) bool {
if err != nil {
log.Fatal(err)
return false
}
return true
}
func GetRootDir() string {
_, b, _, _ := runtime.Caller(0)
dir := filepath.Dir(b)
return filepath.Dir(filepath.Dir(dir))
}
func GetAssets() string {
return GetRootDir()
}
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(hash), err
}
func CheckPasswordHash(password, hash string) error {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err
}
func RandHex() string {
bytes := make([]byte, 12)
rand.Read(bytes)
return hex.EncodeToString(bytes)
}
func Bytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}

View File

@@ -0,0 +1,35 @@
package helpers_test
import (
"testing"
"git.1248.nz/1248/Otfe/misc/helpers"
"git.1248.nz/1248/Otfe/models"
)
func TestGetRootDir(t *testing.T) {
t.Log("Root path:", helpers.GetRootDir())
}
func TestHashPassword(t *testing.T) {
user := models.User{Email: "a@a.com", Username: "a"}
user.Delete("username", "a")
var err error
password := "43539jgifdkvnm4935078uJKJR**$ufjqd98438uiAHFJean89q34JKDFJ"
user.Password, err = helpers.HashPassword(password)
if err != nil {
t.Fail()
}
user.Create()
var user2 models.User
user2.Read("username", "a")
t.Log(helpers.CheckPasswordHash(password, user2.Password))
}
func TestRandHex(t *testing.T) {
for i := 0; i < 20; i++ {
t.Log(helpers.RandHex())
}
}

36
misc/helpers/test.go Normal file
View File

@@ -0,0 +1,36 @@
package helpers
import (
"fmt"
"path/filepath"
"reflect"
"runtime"
"testing"
)
// assert fails the test if the condition is false.
func Assert(tb testing.TB, condition bool, msg string, v ...interface{}) {
if !condition {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d: "+msg+"\033[39m\n\n", append([]interface{}{filepath.Base(file), line}, v...)...)
tb.FailNow()
}
}
// ok fails the test if an err is not nil.
func Ok(tb testing.TB, err error) {
if err != nil {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d: unexpected error: %s\033[39m\n\n", filepath.Base(file), line, err.Error())
tb.FailNow()
}
}
// equals fails the test if exp is not equal to act.
func Equals(tb testing.TB, exp, act interface{}) {
if !reflect.DeepEqual(exp, act) {
_, file, line, _ := runtime.Caller(1)
fmt.Printf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n", filepath.Base(file), line, exp, act)
tb.FailNow()
}
}