Open platform to collect and prioritize feedback
feature: implement user API Key (#492)
Guilherme Oenning0e43dd86a4b7
diff --git a/app/actions/invite.go b/app/actions/invite.goindex 9b790268a..4033bfdee 100644--- a/app/actions/invite.go+++ b/app/actions/invite.go@@ -69,7 +69,7 @@ func (input *InviteUsers) Validate(user *models.User, services *app.Services) *vif errors.Cause(err) == app.ErrNotFound {input.Invitations = append(input.Invitations, &models.UserInvitation{Email: email,- VerificationKey: models.GenerateVerificationKey(),+ VerificationKey: models.GenerateSecretKey(),})}}diff --git a/app/actions/signin.go b/app/actions/signin.goindex 6f1b9df1a..2140cb58d 100644--- a/app/actions/signin.go+++ b/app/actions/signin.go@@ -14,7 +14,7 @@ type SignInByEmail struct {// Initialize the modelfunc (input *SignInByEmail) Initialize() interface{} {input.Model = new(models.SignInByEmail)- input.Model.VerificationKey = models.GenerateVerificationKey()+ input.Model.VerificationKey = models.GenerateSecretKey()return input.Model}diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex 17bbe1ebb..ef1b07633 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -16,7 +16,7 @@ type CreateTenant struct {// Initialize the modelfunc (input *CreateTenant) Initialize() interface{} {input.Model = new(models.CreateTenant)- input.Model.VerificationKey = models.GenerateVerificationKey()+ input.Model.VerificationKey = models.GenerateSecretKey()return input.Model}diff --git a/app/actions/user.go b/app/actions/user.goindex d5d49665f..1c070f56b 100644--- a/app/actions/user.go+++ b/app/actions/user.go@@ -58,7 +58,7 @@ type ChangeUserEmail struct {// Initialize the modelfunc (input *ChangeUserEmail) Initialize() interface{} {input.Model = new(models.ChangeUserEmail)- input.Model.VerificationKey = models.GenerateVerificationKey()+ input.Model.VerificationKey = models.GenerateSecretKey()return input.Model}diff --git a/app/cmd/migrate.go b/app/cmd/migrate.goindex 6f123ac69..d15ac1dee 100644--- a/app/cmd/migrate.go+++ b/app/cmd/migrate.go@@ -4,7 +4,7 @@ import ("github.com/getfider/fider/app/pkg/dbx""github.com/getfider/fider/app/pkg/log""github.com/getfider/fider/app/pkg/log/database"- "github.com/getfider/fider/app/pkg/uuid"+ "github.com/getfider/fider/app/pkg/rand")// RunMigrate run all pending migrations on current DATABASE_URL@@ -12,7 +12,7 @@ import (func RunMigrate() int {db := dbx.New()logger := database.NewLogger("MIGRATE", db)- logger.SetProperty(log.PropertyKeyContextID, uuid.NewV4().String())+ logger.SetProperty(log.PropertyKeyContextID, rand.String(32))db.SetLogger(logger)defer db.Close()diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 2291a1276..4f8f7bc3b 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -107,6 +107,7 @@ func routes(r *web.Engine) *web.Engine {ui.Get("/change-email/verify", handlers.VerifyChangeEmailKey())ui.Delete("/_api/user", handlers.DeleteUser())+ ui.Post("/_api/user/regenerate-apikey", handlers.RegenerateAPIKey())ui.Post("/_api/user/settings", handlers.UpdateUserSettings())ui.Post("/_api/user/change-email", handlers.ChangeUserEmail())ui.Post("/_api/notifications/read-all", handlers.ReadAllNotifications())@@ -133,6 +134,7 @@ func routes(r *web.Engine) *web.Engine {ui.Post("/_api/admin/settings/advanced", handlers.UpdateAdvancedSettings())ui.Post("/_api/admin/settings/privacy", handlers.UpdatePrivacy())ui.Post("/_api/admin/oauth", handlers.SaveOAuthConfig())+ ui.Post("/_api/admin/roles/:role/users", handlers.ChangeUserRole())}api := r.Group()@@ -170,7 +172,6 @@ func routes(r *web.Engine) *web.Engine {api.Post("/api/v1/tags", apiv1.CreateEditTag())api.Put("/api/v1/tags/:slug", apiv1.CreateEditTag())api.Delete("/api/v1/tags/:slug", apiv1.DeleteTag())- api.Post("/api/v1/roles/:role/users", handlers.ChangeUserRole())}return rdiff --git a/app/handlers/oauth.go b/app/handlers/oauth.goindex 4b22a9173..6bc47420c 100644--- a/app/handlers/oauth.go+++ b/app/handlers/oauth.go@@ -10,7 +10,7 @@ import ("github.com/getfider/fider/app/models""github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/jwt"- "github.com/getfider/fider/app/pkg/uuid"+ "github.com/getfider/fider/app/pkg/rand""github.com/getfider/fider/app/pkg/web""github.com/getfider/fider/app/pkg/web/util")@@ -210,7 +210,7 @@ func OAuthCallback() web.HandlerFunc {func SignInByOAuth() web.HandlerFunc {return func(c web.Context) error {provider := c.Param("provider")- identifier := uuid.NewV4().String()+ identifier := rand.String(16)c.AddCookie(web.CookieOAuthIdentifier, identifier, time.Now().Add(2*time.Hour))diff --git a/app/handlers/settings.go b/app/handlers/settings.goindex 35c8632fd..a20f90980 100644--- a/app/handlers/settings.go+++ b/app/handlers/settings.go@@ -122,3 +122,17 @@ func DeleteUser() web.HandlerFunc {return c.Ok(web.Map{})}}++// RegenerateAPIKey regenerates current user's API Key+func RegenerateAPIKey() web.HandlerFunc {+ return func(c web.Context) error {+ apiKey, err := c.Services().Users.RegenerateAPIKey()+ if err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{+ "apiKey": apiKey,+ })+ }+}diff --git a/app/middlewares/domain.go b/app/middlewares/domain.goindex 69013987e..baf1b7fca 100644--- a/app/middlewares/domain.go+++ b/app/middlewares/domain.go@@ -2,6 +2,7 @@ package middlewaresimport ("fmt"+ "strings""github.com/getfider/fider/app/models"@@ -93,7 +94,10 @@ func RequireTenant() web.MiddlewareFunc {func User() web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {return func(c web.Context) error {- var token string+ var (+ token string+ user *models.User+ )cookie, err := c.Request.Cookie(web.CookieAuthName)if err == nil {@@ -113,7 +117,7 @@ func User() web.MiddlewareFunc {return next(c)}- user, err := c.Services().Users.GetByID(claims.UserID)+ user, err = c.Services().Users.GetByID(claims.UserID)if err != nil {if errors.Cause(err) == app.ErrNotFound {c.RemoveCookie(web.CookieAuthName)@@ -121,12 +125,25 @@ func User() web.MiddlewareFunc {}return err}-- if c.Tenant() != nil && user.Tenant.ID == c.Tenant().ID {- c.SetUser(user)+ } else {+ authHeader := c.Request.GetHeader("Authorization")+ parts := strings.Split(authHeader, "Bearer")+ if len(parts) == 2 {+ apiKey := strings.TrimSpace(parts[1])+ user, err = c.Services().Users.GetByAPIKey(apiKey)+ if err != nil {+ if errors.Cause(err) == app.ErrNotFound {+ return next(c)+ }+ return err+ }}}+ if user != nil && c.Tenant() != nil && user.Tenant.ID == c.Tenant().ID {+ c.SetUser(user)+ }+return next(c)}}diff --git a/app/models/identity.go b/app/models/identity.goindex 53d3b6067..b36239acf 100644--- a/app/models/identity.go+++ b/app/models/identity.go@@ -1,11 +1,10 @@package modelsimport (- "strings""time""github.com/getfider/fider/app/pkg/jwt"- "github.com/getfider/fider/app/pkg/uuid"+ "github.com/getfider/fider/app/pkg/rand")//Tenant represents a tenant@@ -294,7 +293,7 @@ type InviteUsers struct {Recipients []string `json:"recipients" format:"lower"`}-// GenerateVerificationKey used on email verifications-func GenerateVerificationKey() string {- return strings.Replace(uuid.NewV4().String(), "-", "", 4)+// GenerateSecretKey returns a 64 chars key+func GenerateSecretKey() string {+ return rand.String(64)}diff --git a/app/models/infra.go b/app/models/infra.goindex 7b4567877..438879562 100644--- a/app/models/infra.go+++ b/app/models/infra.go@@ -92,3 +92,8 @@ var (//OAuthConfigEnabled is used to enable an OAuthConfig for public useOAuthConfigEnabled = 2)++// APIAuthorize is used during API Authorize process+type APIAuthorize struct {+ APIKey string `json:"apiKey"`+}diff --git a/app/pkg/rand/random.go b/app/pkg/rand/random.goindex fc55930e2..89beda03f 100644--- a/app/pkg/rand/random.go+++ b/app/pkg/rand/random.go@@ -9,22 +9,17 @@ func init() {rand.Seed(time.Now().UnixNano())}-var letterRunes = []byte("123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")--// Int returns a random integer-func Int(min, max int) int {- return min + rand.Intn(max-min)-}+var chars = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")// String returns a random string of given length-func String(lenght int) string {- if lenght <= 0 {+func String(n int) string {+ if n <= 0 {return ""}- bytes := make([]byte, lenght)- for i := 0; i < lenght; i++ {- bytes[i] = letterRunes[Int(0, len(letterRunes))]+ bytes := make([]byte, n)+ for i := 0; i < n; i++ {+ bytes[i] = chars[rand.Intn(len(chars))]}return string(bytes)diff --git a/app/pkg/rand/random_test.go b/app/pkg/rand/random_test.goindex 0407fe11d..45a61b7db 100644--- a/app/pkg/rand/random_test.go+++ b/app/pkg/rand/random_test.go@@ -7,8 +7,6 @@ import ("github.com/getfider/fider/app/pkg/rand")-var letterRunes = []rune("123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")-func TestRandomString(t *testing.T) {RegisterT(t)diff --git a/app/pkg/uuid/uuid.go b/app/pkg/uuid/uuid.godeleted file mode 100644index f14fa94e1..000000000--- a/app/pkg/uuid/uuid.go+++ /dev/null@@ -1,481 +0,0 @@-// Copyright (C) 2013-2015 by Maxim Bublis <[email protected]>-//-// Permission is hereby granted, free of charge, to any person obtaining-// a copy of this software and associated documentation files (the-// "Software"), to deal in the Software without restriction, including-// without limitation the rights to use, copy, modify, merge, publish,-// distribute, sublicense, and/or sell copies of the Software, and to-// permit persons to whom the Software is furnished to do so, subject to-// the following conditions:-//-// The above copyright notice and this permission notice shall be-// included in all copies or substantial portions of the Software.-//-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.--// Package uuid provides implementation of Universally Unique Identifier (UUID).-// Supported versions are 1, 3, 4 and 5 (as specified in RFC 4122) and-// version 2 (as specified in DCE 1.1).-package uuid--import (- "bytes"- "crypto/md5"- "crypto/rand"- "crypto/sha1"- "database/sql/driver"- "encoding/binary"- "encoding/hex"- "fmt"- "hash"- "net"- "os"- "sync"- "time"-)--// UUID layout variants.-const (- VariantNCS = iota- VariantRFC4122- VariantMicrosoft- VariantFuture-)--// UUID DCE domains.-const (- DomainPerson = iota- DomainGroup- DomainOrg-)--// Difference in 100-nanosecond intervals between-// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).-const epochStart = 122192928000000000--// Used in string method conversion-const dash byte = '-'--// UUID v1/v2 storage.-var (- storageMutex sync.Mutex- storageOnce sync.Once- epochFunc = unixTimeFunc- clockSequence uint16- lastTime uint64- hardwareAddr [6]byte- posixUID = uint32(os.Getuid())- posixGID = uint32(os.Getgid())-)--// String parse helpers.-var (- urnPrefix = []byte("urn:uuid:")- byteGroups = []int{8, 4, 4, 4, 12}-)--func initClockSequence() {- buf := make([]byte, 2)- safeRandom(buf)- clockSequence = binary.BigEndian.Uint16(buf)-}--func initHardwareAddr() {- interfaces, err := net.Interfaces()- if err == nil {- for _, iface := range interfaces {- if len(iface.HardwareAddr) >= 6 {- copy(hardwareAddr[:], iface.HardwareAddr)- return- }- }- }-- // Initialize hardwareAddr randomly in case- // of real network interfaces absence- safeRandom(hardwareAddr[:])-- // Set multicast bit as recommended in RFC 4122- hardwareAddr[0] |= 0x01-}--func initStorage() {- initClockSequence()- initHardwareAddr()-}--func safeRandom(dest []byte) {- if _, err := rand.Read(dest); err != nil {- panic(err)- }-}--// Returns difference in 100-nanosecond intervals between-// UUID epoch (October 15, 1582) and current time.-// This is default epoch calculation function.-func unixTimeFunc() uint64 {- return epochStart + uint64(time.Now().UnixNano()/100)-}--// UUID representation compliant with specification-// described in RFC 4122.-type UUID [16]byte--// NullUUID can be used with the standard sql package to represent a-// UUID value that can be NULL in the database-type NullUUID struct {- UUID UUID- Valid bool-}--// Nil is the nil UUID is special form of UUID that is specified to have all-// 128 bits set to zero.-var Nil = UUID{}--// Predefined namespace UUIDs.-var (- NamespaceDNS, _ = FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")- NamespaceURL, _ = FromString("6ba7b811-9dad-11d1-80b4-00c04fd430c8")- NamespaceOID, _ = FromString("6ba7b812-9dad-11d1-80b4-00c04fd430c8")- NamespaceX500, _ = FromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8")-)--// And returns result of binary AND of two UUIDs.-func And(u1 UUID, u2 UUID) UUID {- u := UUID{}- for i := 0; i < 16; i++ {- u[i] = u1[i] & u2[i]- }- return u-}--// Or returns result of binary OR of two UUIDs.-func Or(u1 UUID, u2 UUID) UUID {- u := UUID{}- for i := 0; i < 16; i++ {- u[i] = u1[i] | u2[i]- }- return u-}--// Equal returns true if u1 and u2 equals, otherwise returns false.-func Equal(u1 UUID, u2 UUID) bool {- return bytes.Equal(u1[:], u2[:])-}--// Version returns algorithm version used to generate UUID.-func (u UUID) Version() uint {- return uint(u[6] >> 4)-}--// Variant returns UUID layout variant.-func (u UUID) Variant() uint {- switch {- case (u[8] & 0x80) == 0x00:- return VariantNCS- case (u[8]&0xc0)|0x80 == 0x80:- return VariantRFC4122- case (u[8]&0xe0)|0xc0 == 0xc0:- return VariantMicrosoft- }- return VariantFuture-}--// Bytes returns bytes slice representation of UUID.-func (u UUID) Bytes() []byte {- return u[:]-}--// Returns canonical string representation of UUID:-// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.-func (u UUID) String() string {- buf := make([]byte, 36)-- hex.Encode(buf[0:8], u[0:4])- buf[8] = dash- hex.Encode(buf[9:13], u[4:6])- buf[13] = dash- hex.Encode(buf[14:18], u[6:8])- buf[18] = dash- hex.Encode(buf[19:23], u[8:10])- buf[23] = dash- hex.Encode(buf[24:], u[10:])-- return string(buf)-}--// SetVersion sets version bits.-func (u *UUID) SetVersion(v byte) {- u[6] = (u[6] & 0x0f) | (v << 4)-}--// SetVariant sets variant bits as described in RFC 4122.-func (u *UUID) SetVariant() {- u[8] = (u[8] & 0xbf) | 0x80-}--// MarshalText implements the encoding.TextMarshaler interface.-// The encoding is the same as returned by String.-func (u UUID) MarshalText() (text []byte, err error) {- text = []byte(u.String())- return-}--// UnmarshalText implements the encoding.TextUnmarshaler interface.-// Following formats are supported:-// "6ba7b810-9dad-11d1-80b4-00c04fd430c8",-// "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",-// "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"-func (u *UUID) UnmarshalText(text []byte) (err error) {- if len(text) < 32 {- err = fmt.Errorf("uuid: UUID string too short: %s", text)- return- }-- t := text[:]- braced := false-- if bytes.Equal(t[:9], urnPrefix) {- t = t[9:]- } else if t[0] == '{' {- braced = true- t = t[1:]- }-- b := u[:]-- for i, byteGroup := range byteGroups {- if i > 0 {- if t[0] != '-' {- err = fmt.Errorf("uuid: invalid string format")- return- }- t = t[1:]- }-- if len(t) < byteGroup {- err = fmt.Errorf("uuid: UUID string too short: %s", text)- return- }-- if i == 4 && len(t) > byteGroup &&- ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) {- err = fmt.Errorf("uuid: UUID string too long: %s", text)- return- }-- _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup])- if err != nil {- return- }-- t = t[byteGroup:]- b = b[byteGroup/2:]- }-- return-}--// MarshalBinary implements the encoding.BinaryMarshaler interface.-func (u UUID) MarshalBinary() (data []byte, err error) {- data = u.Bytes()- return-}--// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.-// It will return error if the slice isn't 16 bytes long.-func (u *UUID) UnmarshalBinary(data []byte) (err error) {- if len(data) != 16 {- err = fmt.Errorf("uuid: UUID must be exactly 16 bytes long, got %d bytes", len(data))- return- }- copy(u[:], data)-- return-}--// Value implements the driver.Valuer interface.-func (u UUID) Value() (driver.Value, error) {- return u.String(), nil-}--// Scan implements the sql.Scanner interface.-// A 16-byte slice is handled by UnmarshalBinary, while-// a longer byte slice or a string is handled by UnmarshalText.-func (u *UUID) Scan(src interface{}) error {- switch src := src.(type) {- case []byte:- if len(src) == 16 {- return u.UnmarshalBinary(src)- }- return u.UnmarshalText(src)-- case string:- return u.UnmarshalText([]byte(src))- }-- return fmt.Errorf("uuid: cannot convert %T to UUID", src)-}--// Value implements the driver.Valuer interface.-func (u NullUUID) Value() (driver.Value, error) {- if !u.Valid {- return nil, nil- }- // Delegate to UUID Value function- return u.UUID.Value()-}--// Scan implements the sql.Scanner interface.-func (u *NullUUID) Scan(src interface{}) error {- if src == nil {- u.UUID, u.Valid = Nil, false- return nil- }-- // Delegate to UUID Scan function- u.Valid = true- return u.UUID.Scan(src)-}--// FromBytes returns UUID converted from raw byte slice input.-// It will return error if the slice isn't 16 bytes long.-func FromBytes(input []byte) (u UUID, err error) {- err = u.UnmarshalBinary(input)- return-}--// FromBytesOrNil returns UUID converted from raw byte slice input.-// Same behavior as FromBytes, but returns a Nil UUID on error.-func FromBytesOrNil(input []byte) UUID {- uuid, err := FromBytes(input)- if err != nil {- return Nil- }- return uuid-}--// FromString returns UUID parsed from string input.-// Input is expected in a form accepted by UnmarshalText.-func FromString(input string) (u UUID, err error) {- err = u.UnmarshalText([]byte(input))- return-}--// FromStringOrNil returns UUID parsed from string input.-// Same behavior as FromString, but returns a Nil UUID on error.-func FromStringOrNil(input string) UUID {- uuid, err := FromString(input)- if err != nil {- return Nil- }- return uuid-}--// Returns UUID v1/v2 storage state.-// Returns epoch timestamp, clock sequence, and hardware address.-func getStorage() (uint64, uint16, []byte) {- storageOnce.Do(initStorage)-- storageMutex.Lock()- defer storageMutex.Unlock()-- timeNow := epochFunc()- // Clock changed backwards since last UUID generation.- // Should increase clock sequence.- if timeNow <= lastTime {- clockSequence++- }- lastTime = timeNow-- return timeNow, clockSequence, hardwareAddr[:]-}--// NewV1 returns UUID based on current timestamp and MAC address.-func NewV1() UUID {- u := UUID{}-- timeNow, clockSeq, hardwareAddr := getStorage()-- binary.BigEndian.PutUint32(u[0:], uint32(timeNow))- binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))- binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))- binary.BigEndian.PutUint16(u[8:], clockSeq)-- copy(u[10:], hardwareAddr)-- u.SetVersion(1)- u.SetVariant()-- return u-}--// NewV2 returns DCE Security UUID based on POSIX UID/GID.-func NewV2(domain byte) UUID {- u := UUID{}-- timeNow, clockSeq, hardwareAddr := getStorage()-- switch domain {- case DomainPerson:- binary.BigEndian.PutUint32(u[0:], posixUID)- case DomainGroup:- binary.BigEndian.PutUint32(u[0:], posixGID)- }-- binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))- binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))- binary.BigEndian.PutUint16(u[8:], clockSeq)- u[9] = domain-- copy(u[10:], hardwareAddr)-- u.SetVersion(2)- u.SetVariant()-- return u-}--// NewV3 returns UUID based on MD5 hash of namespace UUID and name.-func NewV3(ns UUID, name string) UUID {- u := newFromHash(md5.New(), ns, name)- u.SetVersion(3)- u.SetVariant()-- return u-}--// NewV4 returns random generated UUID.-func NewV4() UUID {- u := UUID{}- safeRandom(u[:])- u.SetVersion(4)- u.SetVariant()-- return u-}--// NewV5 returns UUID based on SHA-1 hash of namespace UUID and name.-func NewV5(ns UUID, name string) UUID {- u := newFromHash(sha1.New(), ns, name)- u.SetVersion(5)- u.SetVariant()-- return u-}--// Returns UUID based on hashing of namespace UUID and name.-func newFromHash(h hash.Hash, ns UUID, name string) UUID {- u := UUID{}- h.Write(ns[:])- h.Write([]byte(name))- copy(u[:], h.Sum(nil))-- return u-}diff --git a/app/pkg/uuid/uuid_test.go b/app/pkg/uuid/uuid_test.godeleted file mode 100644index 56504808f..000000000--- a/app/pkg/uuid/uuid_test.go+++ /dev/null@@ -1,633 +0,0 @@-// Copyright (C) 2013, 2015 by Maxim Bublis <[email protected]>-//-// Permission is hereby granted, free of charge, to any person obtaining-// a copy of this software and associated documentation files (the-// "Software"), to deal in the Software without restriction, including-// without limitation the rights to use, copy, modify, merge, publish,-// distribute, sublicense, and/or sell copies of the Software, and to-// permit persons to whom the Software is furnished to do so, subject to-// the following conditions:-//-// The above copyright notice and this permission notice shall be-// included in all copies or substantial portions of the Software.-//-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.--package uuid--import (- "bytes"- "testing"-)--func TestBytes(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- bytes1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- if !bytes.Equal(u.Bytes(), bytes1) {- t.Errorf("Incorrect bytes representation for UUID: %s", u)- }-}--func TestString(t *testing.T) {- if NamespaceDNS.String() != "6ba7b810-9dad-11d1-80b4-00c04fd430c8" {- t.Errorf("Incorrect string representation for UUID: %s", NamespaceDNS.String())- }-}--func TestEqual(t *testing.T) {- if !Equal(NamespaceDNS, NamespaceDNS) {- t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceDNS)- }-- if Equal(NamespaceDNS, NamespaceURL) {- t.Errorf("Incorrect comparison of %s and %s", NamespaceDNS, NamespaceURL)- }-}--func TestOr(t *testing.T) {- u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff}- u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00}-- u := UUID{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}-- if !Equal(u, Or(u1, u2)) {- t.Errorf("Incorrect bitwise OR result %s", Or(u1, u2))- }-}--func TestAnd(t *testing.T) {- u1 := UUID{0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff}- u2 := UUID{0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00}-- u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}-- if !Equal(u, And(u1, u2)) {- t.Errorf("Incorrect bitwise AND result %s", And(u1, u2))- }-}--func TestVersion(t *testing.T) {- u := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}-- if u.Version() != 1 {- t.Errorf("Incorrect version for UUID: %d", u.Version())- }-}--func TestSetVersion(t *testing.T) {- u := UUID{}- u.SetVersion(4)-- if u.Version() != 4 {- t.Errorf("Incorrect version for UUID after u.setVersion(4): %d", u.Version())- }-}--func TestVariant(t *testing.T) {- u1 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}-- if u1.Variant() != VariantNCS {- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantNCS, u1.Variant())- }-- u2 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}-- if u2.Variant() != VariantRFC4122 {- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantRFC4122, u2.Variant())- }-- u3 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}-- if u3.Variant() != VariantMicrosoft {- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantMicrosoft, u3.Variant())- }-- u4 := UUID{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}-- if u4.Variant() != VariantFuture {- t.Errorf("Incorrect variant for UUID variant %d: %d", VariantFuture, u4.Variant())- }-}--func TestSetVariant(t *testing.T) {- u := new(UUID)- u.SetVariant()-- if u.Variant() != VariantRFC4122 {- t.Errorf("Incorrect variant for UUID after u.setVariant(): %d", u.Variant())- }-}--func TestFromBytes(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- u1, err := FromBytes(b1)- if err != nil {- t.Errorf("Error parsing UUID from bytes: %s", err)- }-- if !Equal(u, u1) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1)- }-- b2 := []byte{}-- _, err = FromBytes(b2)- if err == nil {- t.Errorf("Should return error parsing from empty byte slice, got %s", err)- }-}--func TestMarshalBinary(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- b2, err := u.MarshalBinary()- if err != nil {- t.Errorf("Error marshaling UUID: %s", err)- }-- if !bytes.Equal(b1, b2) {- t.Errorf("Marshaled UUID should be %s, got %s", b1, b2)- }-}--func TestUnmarshalBinary(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- u1 := UUID{}- err := u1.UnmarshalBinary(b1)- if err != nil {- t.Errorf("Error unmarshaling UUID: %s", err)- }-- if !Equal(u, u1) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1)- }-- b2 := []byte{}- u2 := UUID{}-- err = u2.UnmarshalBinary(b2)- if err == nil {- t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err)- }-}--func TestFromString(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"- s2 := "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}"- s3 := "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8"-- _, err := FromString("")- if err == nil {- t.Errorf("Should return error trying to parse empty string, got %s", err)- }-- u1, err := FromString(s1)- if err != nil {- t.Errorf("Error parsing UUID from string: %s", err)- }-- if !Equal(u, u1) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1)- }-- u2, err := FromString(s2)- if err != nil {- t.Errorf("Error parsing UUID from string: %s", err)- }-- if !Equal(u, u2) {- t.Errorf("UUIDs should be equal: %s and %s", u, u2)- }-- u3, err := FromString(s3)- if err != nil {- t.Errorf("Error parsing UUID from string: %s", err)- }-- if !Equal(u, u3) {- t.Errorf("UUIDs should be equal: %s and %s", u, u3)- }-}--func TestFromStringShort(t *testing.T) {- // Invalid 35-character UUID string- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c"-- for i := len(s1); i >= 0; i-- {- _, err := FromString(s1[:i])- if err == nil {- t.Errorf("Should return error trying to parse too short string, got %s", err)- }- }-}--func TestFromStringLong(t *testing.T) {- // Invalid 37+ character UUID string- s := []string{- "6ba7b810-9dad-11d1-80b4-00c04fd430c8=",- "6ba7b810-9dad-11d1-80b4-00c04fd430c8}",- "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}f",- "6ba7b810-9dad-11d1-80b4-00c04fd430c800c04fd430c8",- }-- for _, str := range s {- _, err := FromString(str)- if err == nil {- t.Errorf("Should return error trying to parse too long string, passed %s", str)- }- }-}--func TestFromStringInvalid(t *testing.T) {- // Invalid UUID string formats- s := []string{- "6ba7b8109dad11d180b400c04fd430c8",- "6ba7b8109dad11d180b400c04fd430c86ba7b8109dad11d180b400c04fd430c8",- "urn:uuid:{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",- "6ba7b8109-dad-11d1-80b4-00c04fd430c8",- "6ba7b810-9dad1-1d1-80b4-00c04fd430c8",- "6ba7b810-9dad-11d18-0b4-00c04fd430c8",- "6ba7b810-9dad-11d1-80b40-0c04fd430c8",- "6ba7b810+9dad+11d1+80b4+00c04fd430c8",- "6ba7b810-9dad11d180b400c04fd430c8",- "6ba7b8109dad-11d180b400c04fd430c8",- "6ba7b8109dad11d1-80b400c04fd430c8",- "6ba7b8109dad11d180b4-00c04fd430c8",- }-- for _, str := range s {- _, err := FromString(str)- if err == nil {- t.Errorf("Should return error trying to parse invalid string, passed %s", str)- }- }-}--func TestFromStringOrNil(t *testing.T) {- u := FromStringOrNil("")- if u != Nil {- t.Errorf("Should return Nil UUID on parse failure, got %s", u)- }-}--func TestFromBytesOrNil(t *testing.T) {- b := []byte{}- u := FromBytesOrNil(b)- if u != Nil {- t.Errorf("Should return Nil UUID on parse failure, got %s", u)- }-}--func TestMarshalText(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")-- b2, err := u.MarshalText()- if err != nil {- t.Errorf("Error marshaling UUID: %s", err)- }-- if !bytes.Equal(b1, b2) {- t.Errorf("Marshaled UUID should be %s, got %s", b1, b2)- }-}--func TestUnmarshalText(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")-- u1 := UUID{}- err := u1.UnmarshalText(b1)- if err != nil {- t.Errorf("Error unmarshaling UUID: %s", err)- }-- if !Equal(u, u1) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1)- }-- b2 := []byte("")- u2 := UUID{}-- err = u2.UnmarshalText(b2)- if err == nil {- t.Errorf("Should return error trying to unmarshal from empty string")- }-}--func TestValue(t *testing.T) {- u, err := FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")- if err != nil {- t.Errorf("Error parsing UUID from string: %s", err)- }-- val, err := u.Value()- if err != nil {- t.Errorf("Error getting UUID value: %s", err)- }-- if val != u.String() {- t.Errorf("Wrong value returned, should be equal: %s and %s", val, u)- }-}--func TestValueNil(t *testing.T) {- u := UUID{}-- val, err := u.Value()- if err != nil {- t.Errorf("Error getting UUID value: %s", err)- }-- if val != Nil.String() {- t.Errorf("Wrong value returned, should be equal to UUID.Nil: %s", val)- }-}--func TestNullUUIDValueNil(t *testing.T) {- u := NullUUID{}-- val, err := u.Value()- if err != nil {- t.Errorf("Error getting UUID value: %s", err)- }-- if val != nil {- t.Errorf("Wrong value returned, should be nil: %s", val)- }-}--func TestScanBinary(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- b1 := []byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- u1 := UUID{}- err := u1.Scan(b1)- if err != nil {- t.Errorf("Error unmarshaling UUID: %s", err)- }-- if !Equal(u, u1) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1)- }-- b2 := []byte{}- u2 := UUID{}-- err = u2.Scan(b2)- if err == nil {- t.Errorf("Should return error unmarshalling from empty byte slice, got %s", err)- }-}--func TestScanString(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"-- u1 := UUID{}- err := u1.Scan(s1)- if err != nil {- t.Errorf("Error unmarshaling UUID: %s", err)- }-- if !Equal(u, u1) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1)- }-- s2 := ""- u2 := UUID{}-- err = u2.Scan(s2)- if err == nil {- t.Errorf("Should return error trying to unmarshal from empty string")- }-}--func TestScanText(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- b1 := []byte("6ba7b810-9dad-11d1-80b4-00c04fd430c8")-- u1 := UUID{}- err := u1.Scan(b1)- if err != nil {- t.Errorf("Error unmarshaling UUID: %s", err)- }-- if !Equal(u, u1) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1)- }-- b2 := []byte("")- u2 := UUID{}-- err = u2.Scan(b2)- if err == nil {- t.Errorf("Should return error trying to unmarshal from empty string")- }-}--func TestScanUnsupported(t *testing.T) {- u := UUID{}-- err := u.Scan(true)- if err == nil {- t.Errorf("Should return error trying to unmarshal from bool")- }-}--func TestScanNil(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}-- err := u.Scan(nil)- if err == nil {- t.Errorf("Error UUID shouldn't allow unmarshalling from nil")- }-}--func TestNullUUIDScanValid(t *testing.T) {- u := UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}- s1 := "6ba7b810-9dad-11d1-80b4-00c04fd430c8"-- u1 := NullUUID{}- err := u1.Scan(s1)- if err != nil {- t.Errorf("Error unmarshaling NullUUID: %s", err)- }-- if !u1.Valid {- t.Errorf("NullUUID should be valid")- }-- if !Equal(u, u1.UUID) {- t.Errorf("UUIDs should be equal: %s and %s", u, u1.UUID)- }-}--func TestNullUUIDScanNil(t *testing.T) {- u := NullUUID{UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}, true}-- err := u.Scan(nil)- if err != nil {- t.Errorf("Error unmarshaling NullUUID: %s", err)- }-- if u.Valid {- t.Errorf("NullUUID should not be valid")- }-- if !Equal(u.UUID, Nil) {- t.Errorf("NullUUID value should be equal to Nil: %v", u)- }-}--func TestNewV1(t *testing.T) {- u := NewV1()-- if u.Version() != 1 {- t.Errorf("UUIDv1 generated with incorrect version: %d", u.Version())- }-- if u.Variant() != VariantRFC4122 {- t.Errorf("UUIDv1 generated with incorrect variant: %d", u.Variant())- }-- u1 := NewV1()- u2 := NewV1()-- if Equal(u1, u2) {- t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u1, u2)- }-- oldFunc := epochFunc- epochFunc = func() uint64 { return 0 }-- u3 := NewV1()- u4 := NewV1()-- if Equal(u3, u4) {- t.Errorf("UUIDv1 generated two equal UUIDs: %s and %s", u3, u4)- }-- epochFunc = oldFunc-}--func TestNewV2(t *testing.T) {- u1 := NewV2(DomainPerson)-- if u1.Version() != 2 {- t.Errorf("UUIDv2 generated with incorrect version: %d", u1.Version())- }-- if u1.Variant() != VariantRFC4122 {- t.Errorf("UUIDv2 generated with incorrect variant: %d", u1.Variant())- }-- u2 := NewV2(DomainGroup)-- if u2.Version() != 2 {- t.Errorf("UUIDv2 generated with incorrect version: %d", u2.Version())- }-- if u2.Variant() != VariantRFC4122 {- t.Errorf("UUIDv2 generated with incorrect variant: %d", u2.Variant())- }-}--func TestNewV3(t *testing.T) {- u := NewV3(NamespaceDNS, "www.example.com")-- if u.Version() != 3 {- t.Errorf("UUIDv3 generated with incorrect version: %d", u.Version())- }-- if u.Variant() != VariantRFC4122 {- t.Errorf("UUIDv3 generated with incorrect variant: %d", u.Variant())- }-- if u.String() != "5df41881-3aed-3515-88a7-2f4a814cf09e" {- t.Errorf("UUIDv3 generated incorrectly: %s", u.String())- }-- u = NewV3(NamespaceDNS, "python.org")-- if u.String() != "6fa459ea-ee8a-3ca4-894e-db77e160355e" {- t.Errorf("UUIDv3 generated incorrectly: %s", u.String())- }-- u1 := NewV3(NamespaceDNS, "golang.org")- u2 := NewV3(NamespaceDNS, "golang.org")- if !Equal(u1, u2) {- t.Errorf("UUIDv3 generated different UUIDs for same namespace and name: %s and %s", u1, u2)- }-- u3 := NewV3(NamespaceDNS, "example.com")- if Equal(u1, u3) {- t.Errorf("UUIDv3 generated same UUIDs for different names in same namespace: %s and %s", u1, u2)- }-- u4 := NewV3(NamespaceURL, "golang.org")- if Equal(u1, u4) {- t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4)- }-}--func TestNewV4(t *testing.T) {- u := NewV4()-- if u.Version() != 4 {- t.Errorf("UUIDv4 generated with incorrect version: %d", u.Version())- }-- if u.Variant() != VariantRFC4122 {- t.Errorf("UUIDv4 generated with incorrect variant: %d", u.Variant())- }-}--func TestNewV5(t *testing.T) {- u := NewV5(NamespaceDNS, "www.example.com")-- if u.Version() != 5 {- t.Errorf("UUIDv5 generated with incorrect version: %d", u.Version())- }-- if u.Variant() != VariantRFC4122 {- t.Errorf("UUIDv5 generated with incorrect variant: %d", u.Variant())- }-- u = NewV5(NamespaceDNS, "python.org")-- if u.String() != "886313e1-3b8a-5372-9b90-0c9aee199e5d" {- t.Errorf("UUIDv5 generated incorrectly: %s", u.String())- }-- u1 := NewV5(NamespaceDNS, "golang.org")- u2 := NewV5(NamespaceDNS, "golang.org")- if !Equal(u1, u2) {- t.Errorf("UUIDv5 generated different UUIDs for same namespace and name: %s and %s", u1, u2)- }-- u3 := NewV5(NamespaceDNS, "example.com")- if Equal(u1, u3) {- t.Errorf("UUIDv5 generated same UUIDs for different names in same namespace: %s and %s", u1, u2)- }-- u4 := NewV5(NamespaceURL, "golang.org")- if Equal(u1, u4) {- t.Errorf("UUIDv3 generated same UUIDs for sane names in different namespaces: %s and %s", u1, u4)- }-}diff --git a/app/pkg/web/context_test.go b/app/pkg/web/context_test.goindex 813c0b6e3..cc6b2136f 100644--- a/app/pkg/web/context_test.go+++ b/app/pkg/web/context_test.go@@ -50,7 +50,7 @@ func TestContextID(t *testing.T) {ctx := newGetContext("http://demo.test.fider.io:3000", nil)Expect(ctx.ContextID()).IsNotEmpty()- Expect(ctx.ContextID()).HasLen(36)+ Expect(ctx.ContextID()).HasLen(32)}func TestBaseURL(t *testing.T) {diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.goindex a7673c2bf..3b13c6714 100644--- a/app/pkg/web/engine.go+++ b/app/pkg/web/engine.go@@ -16,7 +16,7 @@ import ("github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/log""github.com/getfider/fider/app/pkg/log/database"- "github.com/getfider/fider/app/pkg/uuid"+ "github.com/getfider/fider/app/pkg/rand""github.com/getfider/fider/app/pkg/worker""github.com/julienschmidt/httprouter")@@ -67,10 +67,10 @@ type Engine struct {func New(settings *models.SystemSettings) *Engine {db := dbx.New()logger := database.NewLogger("WEB", db)- logger.SetProperty(log.PropertyKeyContextID, uuid.NewV4().String())+ logger.SetProperty(log.PropertyKeyContextID, rand.String(32))bgLogger := database.NewLogger("BGW", db)- bgLogger.SetProperty(log.PropertyKeyContextID, uuid.NewV4().String())+ bgLogger.SetProperty(log.PropertyKeyContextID, rand.String(32))router := &Engine{mux: httprouter.New(),@@ -163,7 +163,7 @@ func (e *Engine) Stop() error {//NewContext creates and return a new contextfunc (e *Engine) NewContext(res http.ResponseWriter, req *http.Request, params StringMap) Context {- contextID := uuid.NewV4().String()+ contextID := rand.String(32)request := WrapRequest(req)ctxLogger := e.logger.New()ctxLogger.SetProperty(log.PropertyKeyContextID, contextID)diff --git a/app/pkg/worker/context.go b/app/pkg/worker/context.goindex bf45582d5..612de0faf 100644--- a/app/pkg/worker/context.go+++ b/app/pkg/worker/context.go@@ -6,7 +6,7 @@ import ("github.com/getfider/fider/app/pkg/dbx""github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/log"- "github.com/getfider/fider/app/pkg/uuid"+ "github.com/getfider/fider/app/pkg/rand")//Context holds references to services available for jobs@@ -25,7 +25,7 @@ type Context struct {//NewContext creates a new contextfunc NewContext(workerID, taskName string, db *dbx.Database, logger log.Logger) *Context {ctxLogger := logger.New()- contextID := uuid.NewV4().String()+ contextID := rand.String(32)ctxLogger.SetProperty(log.PropertyKeyContextID, contextID)return &Context{diff --git a/app/storage/inmemory/user.go b/app/storage/inmemory/user.goindex 00f550266..d060677b8 100644--- a/app/storage/inmemory/user.go+++ b/app/storage/inmemory/user.go@@ -13,6 +13,7 @@ type UserStorage struct {users []*models.UserlastID intsettingsPerUser map[int]map[string]string+ userByAPIKey map[string]*models.User}// GetByID returns a user based on given id@@ -151,3 +152,27 @@ func (s *UserStorage) Delete() error {s.user.Providers = make([]*models.UserProvider, 0)return nil}++// RegenerateAPIKey generates a new API Key and returns it+func (s *UserStorage) RegenerateAPIKey() (string, error) {+ apiKey := models.GenerateSecretKey()+ if s.userByAPIKey == nil {+ s.userByAPIKey = make(map[string]*models.User)+ }+ s.userByAPIKey[apiKey] = s.user+ return apiKey, nil+}++// GetByAPIKey returns a user based on its API key+func (s *UserStorage) GetByAPIKey(apiKey string) (*models.User, error) {+ if s.userByAPIKey == nil {+ s.userByAPIKey = make(map[string]*models.User)+ }++ for userAPIKey, user := range s.userByAPIKey {+ if userAPIKey == apiKey {+ return user, nil+ }+ }+ return nil, app.ErrNotFound+}diff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.goindex b39066f4f..58198d90d 100644--- a/app/storage/postgres/post.go+++ b/app/storage/postgres/post.go@@ -553,7 +553,8 @@ func (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificatiAND ((set.value IS NULL AND u.role = ANY($3))OR CAST(set.value AS integer) & $4 > 0- )`,+ )+ ORDER by u.id`,event.UserSettingsKeyName,s.tenant.ID,pq.Array(event.DefaultEnabledUserRoles),@@ -578,7 +579,8 @@ func (s *PostStorage) GetActiveSubscribers(number int, channel models.NotificatiAND ((set.value IS NULL AND u.role = ANY($5))OR CAST(set.value AS integer) & $6 > 0- )`,+ )+ ORDER by u.id`,post.ID,models.SubscriberActive,event.UserSettingsKeyName,diff --git a/app/storage/postgres/user.go b/app/storage/postgres/user.goindex 78283bd48..ba9dd8520 100644--- a/app/storage/postgres/user.go+++ b/app/storage/postgres/user.go@@ -317,3 +317,26 @@ func (s *UserStorage) Delete() error {return nil}++// RegenerateAPIKey generates a new API Key and returns it+func (s *UserStorage) RegenerateAPIKey() (string, error) {+ apiKey := models.GenerateSecretKey()++ if _, err := s.trx.Execute(+ "UPDATE users SET api_key = $3, api_key_date = $4 WHERE id = $1 AND tenant_id = $2",+ s.user.ID, s.tenant.ID, apiKey, time.Now(),+ ); err != nil {+ return "", errors.Wrap(err, "failed to update current user's API Key")+ }++ return apiKey, nil+}++// GetByAPIKey returns a user based on its API key+func (s *UserStorage) GetByAPIKey(apiKey string) (*models.User, error) {+ user, err := getUser(s.trx, "api_key = $1 AND tenant_id = $2", apiKey, s.tenant.ID)+ if err != nil {+ return nil, errors.Wrap(err, "failed to get user with API Key '%s'", apiKey)+ }+ return user, nil+}\ No newline at end of filediff --git a/app/storage/postgres/user_test.go b/app/storage/postgres/user_test.goindex a75856943..2e5b930a7 100644--- a/app/storage/postgres/user_test.go+++ b/app/storage/postgres/user_test.go@@ -1,6 +1,7 @@package postgres_testimport (+ "strings""testing""github.com/getfider/fider/app"@@ -326,3 +327,35 @@ func TestUserStorage_Delete(t *testing.T) {Expect(user.Status).Equals(models.UserDeleted)Expect(user.Providers).HasLen(0)}++func TestUserStorage_APIKey(t *testing.T) {+ SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ users.SetCurrentTenant(demoTenant)+ users.SetCurrentUser(jonSnow)++ apiKey, err := users.RegenerateAPIKey()+ Expect(apiKey).HasLen(64)+ Expect(err).IsNil()++ user, err := users.GetByAPIKey(apiKey)+ Expect(user).Equals(jonSnow)+ Expect(err).IsNil()++ //try to get by uppercase key+ user, err = users.GetByAPIKey(strings.ToUpper(apiKey))+ Expect(user).IsNil()+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)++ //regenerate and try to get again+ users.RegenerateAPIKey()+ user, err = users.GetByAPIKey(apiKey)+ Expect(user).IsNil()+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)++ //try to get by some unknown key+ user, err = users.GetByAPIKey("SOME-INVALID-KEY")+ Expect(user).IsNil()+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)+}diff --git a/app/storage/storage.go b/app/storage/storage.goindex b1ee98511..af4f8fa16 100644--- a/app/storage/storage.go+++ b/app/storage/storage.go@@ -54,6 +54,8 @@ type User interface {GetUserSettings() (map[string]string, error)UpdateSettings(settings map[string]string) errorHasSubscribedTo(postID int) (bool, error)+ GetByAPIKey(apiKey string) (*models.User, error)+ RegenerateAPIKey() (string, error)}// Tenant contains read and write operations for tenantsdiff --git a/migrations/201808181931_add_api_key_users.sql b/migrations/201808181931_add_api_key_users.sqlnew file mode 100644index 000000000..724e6b0f6--- /dev/null+++ b/migrations/201808181931_add_api_key_users.sql@@ -0,0 +1,4 @@+ALTER TABLE users ADD api_key VARCHAR(32) NULL;+ALTER TABLE users ADD api_key_date TIMESTAMPTZ NULL;++CREATE UNIQUE INDEX users_api_key ON users (tenant_id, api_key);\ No newline at end of filediff --git a/migrations/201808192103_increase_key_size.sql b/migrations/201808192103_increase_key_size.sqlnew file mode 100644index 000000000..df58a6636--- /dev/null+++ b/migrations/201808192103_increase_key_size.sql@@ -0,0 +1,2 @@+ALTER TABLE users ALTER COLUMN api_key TYPE VARCHAR(64);+ALTER TABLE email_verifications ALTER COLUMN key TYPE VARCHAR(64);diff --git a/public/pages/MySettings/MySettings.page.scss b/public/pages/MySettings/MySettings.page.scssindex fb1f815be..a6da1f0c6 100644--- a/public/pages/MySettings/MySettings.page.scss+++ b/public/pages/MySettings/MySettings.page.scss@@ -23,4 +23,14 @@color: $red;}}++ .l-api-key {+ h4 {+ margin-top: 50px;+ }+ code {+ padding: 5px;+ background-color: $gray-lighter;+ }+ }}\ No newline at end of filediff --git a/public/pages/MySettings/MySettings.page.tsx b/public/pages/MySettings/MySettings.page.tsxindex 0083c69b8..7d2b9f945 100644--- a/public/pages/MySettings/MySettings.page.tsx+++ b/public/pages/MySettings/MySettings.page.tsx@@ -3,7 +3,7 @@ import "./MySettings.page.scss";import * as React from "react";import { Modal, Form, DisplayError, Button, Gravatar, Heading, Field, Input } from "@fider/components";-import { DangerZone, NotificationSettings } from "./";+import { DangerZone, APIKeyForm, NotificationSettings } from "./";import { CurrentUser, UserSettings } from "@fider/models";import { Failure, actions, Fider } from "@fider/services";@@ -170,6 +170,14 @@ export class MySettingsPage extends React.Component<MySettingsPageProps, MySetti</div></div>+ {false && (+ <div className="row">+ <div className="col-lg-7">+ <APIKeyForm />+ </div>+ </div>+ )}+<div className="row"><div className="col-lg-7"><DangerZone />diff --git a/public/pages/MySettings/components/APIKeyForm.tsx b/public/pages/MySettings/components/APIKeyForm.tsxnew file mode 100644index 000000000..e469aa31e--- /dev/null+++ b/public/pages/MySettings/components/APIKeyForm.tsx@@ -0,0 +1,53 @@+import * as React from "react";+import { Button } from "@fider/components";+import { actions } from "@fider/services";++interface APIKeyFormState {+ apiKey?: string;+}++export class APIKeyForm extends React.Component<{}, APIKeyFormState> {+ constructor(props: {}) {+ super(props);+ this.state = {};+ }++ private renegerate = async () => {+ const result = await actions.regenerateAPIKey();+ if (result.ok) {+ this.setState({ apiKey: result.data.apiKey });+ }+ };++ private showAPIKey() {+ return (+ <>+ <p className="info">+ Your new API Key is: <code>{this.state.apiKey}</code>+ </p>+ <p className="info">Stored it securely on your servers and never store it in the client side of your app.</p>+ </>+ );+ }++ public render() {+ return (+ <div className="l-api-key">+ <h4>API Key</h4>+ <p className="info">+ The API Key is only shown whenever generated. If your Key is lost or has been compromised, generated a new one+ and take note of it.+ </p>+ <p className="info">+ To learn how to use the API, read the <a href="#">official documentation</a>.+ </p>+ <p>+ <Button size="tiny" onClick={this.renegerate}>+ Regenerate API Key+ </Button>+ </p>+ {this.state.apiKey && this.showAPIKey()}+ </div>+ );+ }+}diff --git a/public/pages/MySettings/index.ts b/public/pages/MySettings/index.tsindex b4ff3c99e..a368ad89e 100644--- a/public/pages/MySettings/index.ts+++ b/public/pages/MySettings/index.ts@@ -1,3 +1,4 @@export * from "./MySettings.page";export * from "./components/NotificationSettings";export * from "./components/DangerZone";+export * from "./components/APIKeyForm";diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex dcf42bbeb..c243342fc 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -69,7 +69,7 @@ export const completeProfile = async (key: string, name: string): Promise<Result};export const changeUserRole = async (userId: number, role: UserRole): Promise<Result> => {- return await http.post(`/api/v1/roles/${role}/users`, {+ return await http.post(`/_api/admin/roles/${role}/users`, {userId});};diff --git a/public/services/actions/user.ts b/public/services/actions/user.tsindex 15eecf320..d7f2af417 100644--- a/public/services/actions/user.ts+++ b/public/services/actions/user.ts@@ -17,3 +17,7 @@ export const changeUserEmail = async (email: string): Promise<Result> => {export const deleteCurrentAccount = async (): Promise<Result> => {return await http.delete("/_api/user");};++export const regenerateAPIKey = async (): Promise<Result<{ apiKey: string }>> => {+ return await http.post<{ apiKey: string }>("/_api/user/regenerate-apikey");+};