Compare commits
10 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
8f7582e1ec | ||
![]() |
bdbbe4adee | ||
![]() |
65478296cb | ||
![]() |
2342f7c5c6 | ||
![]() |
8266c1cff5 | ||
![]() |
c662c625a0 | ||
![]() |
c989648327 | ||
![]() |
a933ac1118 | ||
![]() |
b8afe7abcc | ||
![]() |
3ab02cc4ff |
2
Makefile
2
Makefile
@@ -6,4 +6,4 @@ cmd:
|
||||
clean:
|
||||
rm -rf build
|
||||
test:
|
||||
cd server && go clean --testcache && go test ./...
|
||||
cd server && go clean --testcache && go test -v ./...
|
@@ -7,7 +7,7 @@
|
||||
Authorizer
|
||||
</h1>
|
||||
|
||||
**Authorizer** is an open-source authentication and authorization solution for your applications. Bring your database and have complete control over the user information. You can self-host authorizer instances and connect to any SQL database.
|
||||
**Authorizer** is an open-source authentication and authorization solution for your applications. Bring your database and have complete control over the user information. You can self-host authorizer instances and connect to any database (Currently supports [Postgres](https://www.postgresql.org/), [MySQL](https://www.mysql.com/), [SQLite](https://www.sqlite.org/index.html), [SQLServer](https://www.microsoft.com/en-us/sql-server/), [MongoDB](https://mongodb.com/),[ArangoDB](https://www.arangodb.com/)).
|
||||
|
||||
## Table of contents
|
||||
|
||||
@@ -149,6 +149,10 @@ Deploy production ready Authorizer instance using [railway.app](https://github.c
|
||||
> Note: One can always disable the email verification to allow open sign up, which is not recommended for production as anyone can use anyone's email address 😅
|
||||
- For persisting user sessions, you will need Redis URL (not in case of railway.app). If you do not configure a Redis server, sessions will be persisted until the instance is up or not restarted. For better response time on authorization requests/middleware, we recommend deploying Redis on the same infra/network as your authorizer server.
|
||||
|
||||
## Testing
|
||||
|
||||
- Integration Test: This tests are written along with [authorizer-js](https://github.com/authorizerdev/authorizer-js/blob/main/__test__/index.test.js) lib.
|
||||
|
||||
## Integrating into your website
|
||||
|
||||
This example demonstrates how you can use [`@authorizerdev/authorizer-js`](/authorizer-js/getting-started) CDN version and have login ready for your site in few seconds. You can also use the ES module version of [`@authorizerdev/authorizer-js`](/authorizer-js/getting-started) or framework-specific versions like [`@authorizerdev/authorizer-react`](/authorizer-react/getting-started)
|
||||
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
71
app/package-lock.json
generated
71
app/package-lock.json
generated
@@ -13,9 +13,9 @@
|
||||
}
|
||||
},
|
||||
"@authorizerdev/authorizer-react": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@authorizerdev/authorizer-react/-/authorizer-react-0.1.0.tgz",
|
||||
"integrity": "sha512-+ro0CNKIvblEgRs5M0HevUYrXC6s433GinL7EubIL5XztN48GDBV2GI86lhl4WvjbYTZApZloXWczaZ51g8uig==",
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@authorizerdev/authorizer-react/-/authorizer-react-0.2.0.tgz",
|
||||
"integrity": "sha512-1JICta0rpgDlncIcvilWcYKP8QNq2v0RlcYS6ZeYZGJ5bymFlF6NOdMjh6Hn2IFfSWtqEPQ6zU++kAQ8kei1AA==",
|
||||
"requires": {
|
||||
"@authorizerdev/authorizer-js": "^0.1.0",
|
||||
"final-form": "^4.20.2",
|
||||
@@ -32,9 +32,9 @@
|
||||
}
|
||||
},
|
||||
"@babel/generator": {
|
||||
"version": "7.16.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.0.tgz",
|
||||
"integrity": "sha512-RR8hUCfRQn9j9RPKEVXo9LiwoxLPYn6hNZlvUOR8tSnaxlD0p0+la00ZP9/SnRt6HchKr+X0fO2r8vrETiJGew==",
|
||||
"version": "7.16.5",
|
||||
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.16.5.tgz",
|
||||
"integrity": "sha512-kIvCdjZqcdKqoDbVVdt5R99icaRtrtYhYK/xux5qiWCBmfdvEYMFZ68QCrpE5cbFM1JsuArUNs1ZkuKtTtUcZA==",
|
||||
"requires": {
|
||||
"@babel/types": "^7.16.0",
|
||||
"jsesc": "^2.5.1",
|
||||
@@ -49,6 +49,14 @@
|
||||
"@babel/types": "^7.16.0"
|
||||
}
|
||||
},
|
||||
"@babel/helper-environment-visitor": {
|
||||
"version": "7.16.5",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.16.5.tgz",
|
||||
"integrity": "sha512-ODQyc5AnxmZWm/R2W7fzhamOk1ey8gSguo5SGvF0zcB3uUzRpTRmM/jmLSm9bDMyPlvbyJ+PwPEK0BWIoZ9wjg==",
|
||||
"requires": {
|
||||
"@babel/types": "^7.16.0"
|
||||
}
|
||||
},
|
||||
"@babel/helper-function-name": {
|
||||
"version": "7.16.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.16.0.tgz",
|
||||
@@ -107,9 +115,9 @@
|
||||
}
|
||||
},
|
||||
"@babel/parser": {
|
||||
"version": "7.16.3",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.3.tgz",
|
||||
"integrity": "sha512-dcNwU1O4sx57ClvLBVFbEgx0UZWfd0JQX5X6fxFRCLHelFBGXFfSz6Y0FAq2PEwUqlqLkdVjVr4VASEOuUnLJw=="
|
||||
"version": "7.16.6",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.16.6.tgz",
|
||||
"integrity": "sha512-Gr86ujcNuPDnNOY8mi383Hvi8IYrJVJYuf3XcuBM/Dgd+bINn/7tHqsj+tKkoreMbmGsFLsltI/JJd8fOFWGDQ=="
|
||||
},
|
||||
"@babel/runtime": {
|
||||
"version": "7.14.8",
|
||||
@@ -130,16 +138,17 @@
|
||||
}
|
||||
},
|
||||
"@babel/traverse": {
|
||||
"version": "7.16.3",
|
||||
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.16.3.tgz",
|
||||
"integrity": "sha512-eolumr1vVMjqevCpwVO99yN/LoGL0EyHiLO5I043aYQvwOJ9eR5UsZSClHVCzfhBduMAsSzgA/6AyqPjNayJag==",
|
||||
"version": "7.16.5",
|
||||
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.16.5.tgz",
|
||||
"integrity": "sha512-FOCODAzqUMROikDYLYxl4nmwiLlu85rNqBML/A5hKRVXG2LV8d0iMqgPzdYTcIpjZEBB7D6UDU9vxRZiriASdQ==",
|
||||
"requires": {
|
||||
"@babel/code-frame": "^7.16.0",
|
||||
"@babel/generator": "^7.16.0",
|
||||
"@babel/generator": "^7.16.5",
|
||||
"@babel/helper-environment-visitor": "^7.16.5",
|
||||
"@babel/helper-function-name": "^7.16.0",
|
||||
"@babel/helper-hoist-variables": "^7.16.0",
|
||||
"@babel/helper-split-export-declaration": "^7.16.0",
|
||||
"@babel/parser": "^7.16.3",
|
||||
"@babel/parser": "^7.16.5",
|
||||
"@babel/types": "^7.16.0",
|
||||
"debug": "^4.1.0",
|
||||
"globals": "^11.1.0"
|
||||
@@ -241,12 +250,12 @@
|
||||
}
|
||||
},
|
||||
"babel-plugin-styled-components": {
|
||||
"version": "1.13.3",
|
||||
"resolved": "https://registry.npmjs.org/babel-plugin-styled-components/-/babel-plugin-styled-components-1.13.3.tgz",
|
||||
"integrity": "sha512-meGStRGv+VuKA/q0/jXxrPNWEm4LPfYIqxooDTdmh8kFsP/Ph7jJG5rUPwUPX3QHUvggwdbgdGpo88P/rRYsVw==",
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/babel-plugin-styled-components/-/babel-plugin-styled-components-2.0.2.tgz",
|
||||
"integrity": "sha512-7eG5NE8rChnNTDxa6LQfynwgHTVOYYaHJbUYSlOhk8QBXIQiMBKq4gyfHBBKPrxUcVBXVJL61ihduCpCQbuNbw==",
|
||||
"requires": {
|
||||
"@babel/helper-annotate-as-pure": "^7.15.4",
|
||||
"@babel/helper-module-imports": "^7.15.4",
|
||||
"@babel/helper-annotate-as-pure": "^7.16.0",
|
||||
"@babel/helper-module-imports": "^7.16.0",
|
||||
"babel-plugin-syntax-jsx": "^6.18.0",
|
||||
"lodash": "^4.17.11"
|
||||
}
|
||||
@@ -305,9 +314,9 @@
|
||||
"integrity": "sha512-jXKhWqXPmlUeoQnF/EhTtTl4C9SnrxSH/jZUih3jmO6lBKr99rP3/+FmrMj4EFpOXzMtXHAZkd3x0E6h6Fgflw=="
|
||||
},
|
||||
"debug": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz",
|
||||
"integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==",
|
||||
"version": "4.3.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz",
|
||||
"integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==",
|
||||
"requires": {
|
||||
"ms": "2.1.2"
|
||||
}
|
||||
@@ -323,9 +332,9 @@
|
||||
"integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ="
|
||||
},
|
||||
"final-form": {
|
||||
"version": "4.20.4",
|
||||
"resolved": "https://registry.npmjs.org/final-form/-/final-form-4.20.4.tgz",
|
||||
"integrity": "sha512-hyoOVVilPLpkTvgi+FSJkFZrh0Yhy4BhE6lk/NiBwrF4aRV8/ykKEyXYvQH/pfUbRkOosvpESYouFb+FscsLrw==",
|
||||
"version": "4.20.6",
|
||||
"resolved": "https://registry.npmjs.org/final-form/-/final-form-4.20.6.tgz",
|
||||
"integrity": "sha512-fCdwIj49KOaFfDRlXB57Eo+GghIMZQWrA9TakQI3C9uQxHwaFHXqZSNRlUdfnQmNNeySwGOaGPZCvjy58hyv4w==",
|
||||
"requires": {
|
||||
"@babel/runtime": "^7.10.0"
|
||||
}
|
||||
@@ -432,9 +441,9 @@
|
||||
}
|
||||
},
|
||||
"postcss-value-parser": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.1.0.tgz",
|
||||
"integrity": "sha512-97DXOFbQJhk71ne5/Mt6cOu6yxsSfM0QGQyl0L25Gca4yGWEGJaig7l7gbCX623VqTBNGLRLaVUCnNkcedlRSQ=="
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
|
||||
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="
|
||||
},
|
||||
"prop-types": {
|
||||
"version": "15.7.2",
|
||||
@@ -481,9 +490,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/runtime": {
|
||||
"version": "7.16.3",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.16.3.tgz",
|
||||
"integrity": "sha512-WBwekcqacdY2e9AF/Q7WLFUWmdJGJTkbjqTjoMDgXkVZ3ZRUvOPsLb5KdwISoQVsbP+DQzVZW4Zhci0DvpbNTQ==",
|
||||
"version": "7.16.5",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.16.5.tgz",
|
||||
"integrity": "sha512-TXWihFIS3Pyv5hzR7j6ihmeLkZfrXGxAr5UfSl8CHf+6q/wpiYDkUau0czckpYG8QmnCIuPpdLtuA9VmuGGyMA==",
|
||||
"requires": {
|
||||
"regenerator-runtime": "^0.13.4"
|
||||
}
|
||||
|
@@ -10,7 +10,7 @@
|
||||
"author": "Lakhan Samani",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@authorizerdev/authorizer-react": "^0.1.0",
|
||||
"@authorizerdev/authorizer-react": "^0.2.0",
|
||||
"@types/react": "^17.0.15",
|
||||
"@types/react-dom": "^17.0.9",
|
||||
"esbuild": "^0.12.17",
|
||||
|
@@ -23,7 +23,7 @@ func initArangodb() (arangoDriver.Database, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client, err := arangoDriver.NewClient(arangoDriver.ClientConfig{
|
||||
arangoClient, err := arangoDriver.NewClient(arangoDriver.ClientConfig{
|
||||
Connection: conn,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -32,19 +32,19 @@ func initArangodb() (arangoDriver.Database, error) {
|
||||
|
||||
var arangodb driver.Database
|
||||
|
||||
arangodb_exists, err := client.DatabaseExists(nil, constants.DATABASE_NAME)
|
||||
arangodb_exists, err := arangoClient.DatabaseExists(nil, constants.DATABASE_NAME)
|
||||
|
||||
if arangodb_exists {
|
||||
log.Println(constants.DATABASE_NAME + " db exists already")
|
||||
|
||||
arangodb, err = client.Database(nil, constants.DATABASE_NAME)
|
||||
arangodb, err = arangoClient.Database(nil, constants.DATABASE_NAME)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
} else {
|
||||
arangodb, err = client.CreateDatabase(nil, constants.DATABASE_NAME, nil)
|
||||
arangodb, err = arangoClient.CreateDatabase(nil, constants.DATABASE_NAME, nil)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -89,7 +89,6 @@ func initArangodb() (arangoDriver.Database, error) {
|
||||
Sparse: true,
|
||||
})
|
||||
verificationRequestCollection.EnsureHashIndex(ctx, []string{"token"}, &arangoDriver.EnsureHashIndexOptions{
|
||||
Unique: true,
|
||||
Sparse: true,
|
||||
})
|
||||
|
||||
|
@@ -6,6 +6,7 @@ import (
|
||||
arangoDriver "github.com/arangodb/go-driver"
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/enum"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
@@ -32,6 +33,7 @@ type Manager interface {
|
||||
type manager struct {
|
||||
sqlDB *gorm.DB
|
||||
arangodb arangoDriver.Database
|
||||
mongodb *mongo.Database
|
||||
}
|
||||
|
||||
// mainly used by nosql dbs
|
||||
@@ -42,11 +44,12 @@ type CollectionList struct {
|
||||
}
|
||||
|
||||
var (
|
||||
IsSQL bool
|
||||
IsArangoDB bool
|
||||
Mgr Manager
|
||||
Prefix = "authorizer_"
|
||||
Collections = CollectionList{
|
||||
IsORMSupported bool
|
||||
IsArangoDB bool
|
||||
IsMongoDB bool
|
||||
Mgr Manager
|
||||
Prefix = "authorizer_"
|
||||
Collections = CollectionList{
|
||||
User: Prefix + "users",
|
||||
VerificationRequest: Prefix + "verification_requests",
|
||||
Session: Prefix + "sessions",
|
||||
@@ -57,8 +60,9 @@ func InitDB() {
|
||||
var sqlDB *gorm.DB
|
||||
var err error
|
||||
|
||||
IsSQL = constants.DATABASE_TYPE != enum.Arangodb.String()
|
||||
IsORMSupported = constants.DATABASE_TYPE != enum.Arangodb.String() && constants.DATABASE_TYPE != enum.Mongodb.String()
|
||||
IsArangoDB = constants.DATABASE_TYPE == enum.Arangodb.String()
|
||||
IsMongoDB = constants.DATABASE_TYPE == enum.Mongodb.String()
|
||||
|
||||
// sql db orm config
|
||||
ormConfig := &gorm.Config{
|
||||
@@ -85,19 +89,31 @@ func InitDB() {
|
||||
case enum.Arangodb.String():
|
||||
arangodb, err := initArangodb()
|
||||
if err != nil {
|
||||
log.Fatal("error initing arangodb:", err)
|
||||
log.Fatal("error initializing arangodb:", err)
|
||||
}
|
||||
|
||||
Mgr = &manager{
|
||||
sqlDB: nil,
|
||||
mongodb: nil,
|
||||
arangodb: arangodb,
|
||||
}
|
||||
|
||||
break
|
||||
case enum.Mongodb.String():
|
||||
mongodb, err := initMongodb()
|
||||
if err != nil {
|
||||
log.Fatal("error initializing mongodb connection:", err)
|
||||
}
|
||||
|
||||
Mgr = &manager{
|
||||
sqlDB: nil,
|
||||
arangodb: nil,
|
||||
mongodb: mongodb,
|
||||
}
|
||||
}
|
||||
|
||||
// common for all sql dbs that are configured via gorm
|
||||
if IsSQL {
|
||||
// common for all sql dbs that are configured via go-orm
|
||||
if IsORMSupported {
|
||||
if err != nil {
|
||||
log.Fatal("Failed to init sqlDB:", err)
|
||||
} else {
|
||||
@@ -106,6 +122,7 @@ func InitDB() {
|
||||
Mgr = &manager{
|
||||
sqlDB: sqlDB,
|
||||
arangodb: nil,
|
||||
mongodb: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
81
server/db/mongodb.go
Normal file
81
server/db/mongodb.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||||
)
|
||||
|
||||
func initMongodb() (*mongo.Database, error) {
|
||||
mongodbOptions := options.Client().ApplyURI(constants.DATABASE_URL)
|
||||
maxWait := time.Duration(5 * time.Second)
|
||||
mongodbOptions.ConnectTimeout = &maxWait
|
||||
mongoClient, err := mongo.NewClient(mongodbOptions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
err = mongoClient.Connect(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = mongoClient.Ping(ctx, readpref.Primary())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mongodb := mongoClient.Database(constants.DATABASE_NAME, options.Database())
|
||||
|
||||
mongodb.CreateCollection(ctx, Collections.User, options.CreateCollection())
|
||||
userCollection := mongodb.Collection(Collections.User, options.Collection())
|
||||
userCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
|
||||
mongo.IndexModel{
|
||||
Keys: bson.M{"id": 1},
|
||||
Options: options.Index().SetUnique(true).SetSparse(true),
|
||||
},
|
||||
}, options.CreateIndexes())
|
||||
userCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
|
||||
mongo.IndexModel{
|
||||
Keys: bson.M{"email": 1},
|
||||
Options: options.Index().SetUnique(true).SetSparse(true),
|
||||
},
|
||||
}, options.CreateIndexes())
|
||||
|
||||
mongodb.CreateCollection(ctx, Collections.VerificationRequest, options.CreateCollection())
|
||||
verificationRequestCollection := mongodb.Collection(Collections.VerificationRequest, options.Collection())
|
||||
verificationRequestCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
|
||||
mongo.IndexModel{
|
||||
Keys: bson.M{"id": 1},
|
||||
Options: options.Index().SetUnique(true).SetSparse(true),
|
||||
},
|
||||
}, options.CreateIndexes())
|
||||
verificationRequestCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
|
||||
mongo.IndexModel{
|
||||
Keys: bson.M{"email": 1, "identifier": 1},
|
||||
Options: options.Index().SetUnique(true).SetSparse(true),
|
||||
},
|
||||
}, options.CreateIndexes())
|
||||
verificationRequestCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
|
||||
mongo.IndexModel{
|
||||
Keys: bson.M{"token": 1},
|
||||
Options: options.Index().SetSparse(true),
|
||||
},
|
||||
}, options.CreateIndexes())
|
||||
|
||||
mongodb.CreateCollection(ctx, Collections.Session, options.CreateCollection())
|
||||
sessionCollection := mongodb.Collection(Collections.Session, options.Collection())
|
||||
sessionCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
|
||||
mongo.IndexModel{
|
||||
Keys: bson.M{"id": 1},
|
||||
Options: options.Index().SetUnique(true).SetSparse(true),
|
||||
},
|
||||
}, options.CreateIndexes())
|
||||
|
||||
return mongodb, nil
|
||||
}
|
@@ -5,19 +5,20 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Key string `json:"_key,omitempty"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id"`
|
||||
UserID string `gorm:"type:char(36)" json:"user_id"`
|
||||
User User `json:"-"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
IP string `json:"ip"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
Key string `json:"_key,omitempty" bson:"_key,omitempty"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty" bson:"_id"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id" bson:"id"`
|
||||
UserID string `gorm:"type:char(36)" json:"user_id" bson:"user_id"`
|
||||
User User `json:"-" bson:"-"`
|
||||
UserAgent string `json:"user_agent" bson:"user_agent"`
|
||||
IP string `json:"ip" bson:"ip"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at" bson:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at" bson:"updated_at"`
|
||||
}
|
||||
|
||||
// AddSession function to save user sessiosn
|
||||
@@ -26,16 +27,7 @@ func (mgr *manager) AddSession(session Session) error {
|
||||
session.ID = uuid.New().String()
|
||||
}
|
||||
|
||||
if session.CreatedAt == 0 {
|
||||
session.CreatedAt = time.Now().Unix()
|
||||
}
|
||||
|
||||
if session.UpdatedAt == 0 {
|
||||
session.CreatedAt = time.Now().Unix()
|
||||
}
|
||||
|
||||
if IsSQL {
|
||||
// copy id as value for fields required for mongodb & arangodb
|
||||
if IsORMSupported {
|
||||
session.Key = session.ID
|
||||
session.ObjectID = session.ID
|
||||
res := mgr.sqlDB.Clauses(
|
||||
@@ -49,7 +41,6 @@ func (mgr *manager) AddSession(session Session) error {
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
|
||||
session.CreatedAt = time.Now().Unix()
|
||||
session.UpdatedAt = time.Now().Unix()
|
||||
sessionCollection, _ := mgr.arangodb.Collection(nil, Collections.Session)
|
||||
@@ -60,5 +51,18 @@ func (mgr *manager) AddSession(session Session) error {
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
session.Key = session.ID
|
||||
session.ObjectID = session.ID
|
||||
session.CreatedAt = time.Now().Unix()
|
||||
session.UpdatedAt = time.Now().Unix()
|
||||
sessionCollection := mgr.mongodb.Collection(Collections.Session, options.Collection())
|
||||
_, err := sessionCollection.InsertOne(nil, session)
|
||||
if err != nil {
|
||||
log.Println(`error saving session`, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@@ -1,8 +1,6 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
@@ -10,23 +8,25 @@ import (
|
||||
"github.com/arangodb/go-driver"
|
||||
arangoDriver "github.com/arangodb/go-driver"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Key string `json:"_key,omitempty"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Email string `gorm:"unique" json:"email"`
|
||||
Password string `gorm:"type:text" json:"password"`
|
||||
SignupMethod string `json:"signup_method"`
|
||||
EmailVerifiedAt int64 `json:"email_verified_at"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
Image string `gorm:"type:text" json:"image"`
|
||||
Roles string `json:"roles"`
|
||||
Key string `json:"_key,omitempty" bson:"_key"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty" bson:"_id"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id" bson:"id"`
|
||||
FirstName string `json:"first_name" bson:"first_name"`
|
||||
LastName string `json:"last_name" bson:"last_name"`
|
||||
Email string `gorm:"unique" json:"email" bson:"email"`
|
||||
Password string `gorm:"type:text" json:"password" bson:"password"`
|
||||
SignupMethod string `json:"signup_method" bson:"signup_method"`
|
||||
EmailVerifiedAt int64 `json:"email_verified_at" bson:"email_verified_at"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at" bson:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at" bson:"updated_at"`
|
||||
Image string `gorm:"type:text" json:"image" bson:"image"`
|
||||
Roles string `json:"roles" bson:"roles"`
|
||||
}
|
||||
|
||||
// AddUser function to add user even with email conflict
|
||||
@@ -35,7 +35,7 @@ func (mgr *manager) AddUser(user User) (User, error) {
|
||||
user.ID = uuid.New().String()
|
||||
}
|
||||
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
// copy id as value for fields required for mongodb & arangodb
|
||||
user.Key = user.ID
|
||||
user.ObjectID = user.ID
|
||||
@@ -54,9 +54,8 @@ func (mgr *manager) AddUser(user User) (User, error) {
|
||||
if IsArangoDB {
|
||||
user.CreatedAt = time.Now().Unix()
|
||||
user.UpdatedAt = time.Now().Unix()
|
||||
ctx := context.Background()
|
||||
userCollection, _ := mgr.arangodb.Collection(nil, Collections.User)
|
||||
meta, err := userCollection.CreateDocument(arangoDriver.WithOverwrite(ctx), user)
|
||||
meta, err := userCollection.CreateDocument(arangoDriver.WithOverwrite(nil), user)
|
||||
if err != nil {
|
||||
log.Println("error adding user:", err)
|
||||
return user, err
|
||||
@@ -64,6 +63,20 @@ func (mgr *manager) AddUser(user User) (User, error) {
|
||||
user.Key = meta.Key
|
||||
user.ObjectID = meta.ID.String()
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
user.CreatedAt = time.Now().Unix()
|
||||
user.UpdatedAt = time.Now().Unix()
|
||||
user.Key = user.ID
|
||||
user.ObjectID = user.ID
|
||||
userCollection := mgr.mongodb.Collection(Collections.User, options.Collection())
|
||||
_, err := userCollection.InsertOne(nil, user)
|
||||
if err != nil {
|
||||
log.Println("error adding user:", err)
|
||||
return user, err
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
@@ -71,7 +84,7 @@ func (mgr *manager) AddUser(user User) (User, error) {
|
||||
func (mgr *manager) UpdateUser(user User) (User, error) {
|
||||
user.UpdatedAt = time.Now().Unix()
|
||||
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Save(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
@@ -91,6 +104,16 @@ func (mgr *manager) UpdateUser(user User) (User, error) {
|
||||
user.Key = meta.Key
|
||||
user.ObjectID = meta.ID.String()
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
userCollection := mgr.mongodb.Collection(Collections.User, options.Collection())
|
||||
_, err := userCollection.UpdateOne(nil, bson.M{"id": bson.M{"$eq": user.ID}}, bson.M{"$set": user}, options.MergeUpdateOptions())
|
||||
if err != nil {
|
||||
log.Println("error updating user:", err)
|
||||
return user, err
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
@@ -98,7 +121,7 @@ func (mgr *manager) UpdateUser(user User) (User, error) {
|
||||
func (mgr *manager) GetUsers() ([]User, error) {
|
||||
var users []User
|
||||
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Find(&users)
|
||||
if result.Error != nil {
|
||||
log.Println("error getting users:", result.Error)
|
||||
@@ -126,20 +149,37 @@ func (mgr *manager) GetUsers() ([]User, error) {
|
||||
}
|
||||
|
||||
if meta.Key != "" {
|
||||
user.Key = meta.Key
|
||||
user.ObjectID = meta.ID.String()
|
||||
users = append(users, user)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
userCollection := mgr.mongodb.Collection(Collections.User, options.Collection())
|
||||
cursor, err := userCollection.Find(nil, bson.M{}, options.Find())
|
||||
if err != nil {
|
||||
log.Println("error getting users:", err)
|
||||
return users, err
|
||||
}
|
||||
defer cursor.Close(nil)
|
||||
|
||||
for cursor.Next(nil) {
|
||||
var user User
|
||||
err := cursor.Decode(&user)
|
||||
if err != nil {
|
||||
return users, err
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) GetUserByEmail(email string) (User, error) {
|
||||
var user User
|
||||
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Where("email = ?", email).First(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
@@ -173,13 +213,21 @@ func (mgr *manager) GetUserByEmail(email string) (User, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
userCollection := mgr.mongodb.Collection(Collections.User, options.Collection())
|
||||
err := userCollection.FindOne(nil, bson.M{"email": email}).Decode(&user)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) GetUserByID(id string) (User, error) {
|
||||
var user User
|
||||
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Where("id = ?", id).First(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
@@ -199,11 +247,6 @@ func (mgr *manager) GetUserByID(id string) (User, error) {
|
||||
}
|
||||
defer cursor.Close()
|
||||
|
||||
count := cursor.Count()
|
||||
if count == 0 {
|
||||
return user, errors.New("user not found")
|
||||
}
|
||||
|
||||
for {
|
||||
if !cursor.HasMore() {
|
||||
if user.Key == "" {
|
||||
@@ -218,11 +261,19 @@ func (mgr *manager) GetUserByID(id string) (User, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
userCollection := mgr.mongodb.Collection(Collections.User, options.Collection())
|
||||
err := userCollection.FindOne(nil, bson.M{"id": id}).Decode(&user)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) DeleteUser(user User) error {
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Delete(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
@@ -240,5 +291,14 @@ func (mgr *manager) DeleteUser(user User) error {
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
userCollection := mgr.mongodb.Collection(Collections.User, options.Collection())
|
||||
_, err := userCollection.DeleteOne(nil, bson.M{"id": user.ID}, options.Delete())
|
||||
if err != nil {
|
||||
log.Println("error deleting user:", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@@ -3,22 +3,25 @@ package db
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/arangodb/go-driver"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type VerificationRequest struct {
|
||||
Key string `json:"_key,omitempty"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id"`
|
||||
Token string `gorm:"type:text" json:"token"`
|
||||
Identifier string `gorm:"uniqueIndex:idx_email_identifier" json:"identifier"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
Email string `gorm:"uniqueIndex:idx_email_identifier" json:"email"`
|
||||
Key string `json:"_key,omitempty" bson:"_key"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty" bson:"_id"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id" bson:"id"`
|
||||
Token string `gorm:"type:text" json:"token" bson:"token"`
|
||||
Identifier string `gorm:"uniqueIndex:idx_email_identifier" json:"identifier" bson:"identifier"`
|
||||
ExpiresAt int64 `json:"expires_at" bson:"expires_at"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at" bson:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at" bson:"updated_at"`
|
||||
Email string `gorm:"uniqueIndex:idx_email_identifier" json:"email" bson:"email"`
|
||||
}
|
||||
|
||||
// AddVerification function to add verification record
|
||||
@@ -26,7 +29,7 @@ func (mgr *manager) AddVerification(verification VerificationRequest) (Verificat
|
||||
if verification.ID == "" {
|
||||
verification.ID = uuid.New().String()
|
||||
}
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
// copy id as value for fields required for mongodb & arangodb
|
||||
verification.Key = verification.ID
|
||||
verification.ObjectID = verification.ID
|
||||
@@ -42,14 +45,31 @@ func (mgr *manager) AddVerification(verification VerificationRequest) (Verificat
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
verification.CreatedAt = time.Now().Unix()
|
||||
verification.UpdatedAt = time.Now().Unix()
|
||||
verificationRequestCollection, _ := mgr.arangodb.Collection(nil, Collections.VerificationRequest)
|
||||
meta, err := verificationRequestCollection.CreateDocument(nil, verification)
|
||||
if err != nil {
|
||||
log.Println("error saving verification record:", err)
|
||||
return verification, err
|
||||
}
|
||||
verification.Key = meta.Key
|
||||
verification.ObjectID = meta.ID.String()
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
verification.CreatedAt = time.Now().Unix()
|
||||
verification.UpdatedAt = time.Now().Unix()
|
||||
verification.Key = verification.ID
|
||||
verification.ObjectID = verification.ID
|
||||
verificationRequestCollection := mgr.mongodb.Collection(Collections.VerificationRequest, options.Collection())
|
||||
_, err := verificationRequestCollection.InsertOne(nil, verification)
|
||||
if err != nil {
|
||||
log.Println("error saving verification record:", err)
|
||||
return verification, err
|
||||
}
|
||||
}
|
||||
|
||||
return verification, nil
|
||||
}
|
||||
|
||||
@@ -57,7 +77,7 @@ func (mgr *manager) AddVerification(verification VerificationRequest) (Verificat
|
||||
func (mgr *manager) GetVerificationRequests() ([]VerificationRequest, error) {
|
||||
var verificationRequests []VerificationRequest
|
||||
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Find(&verificationRequests)
|
||||
if result.Error != nil {
|
||||
log.Println("error getting verification requests:", result.Error)
|
||||
@@ -85,20 +105,38 @@ func (mgr *manager) GetVerificationRequests() ([]VerificationRequest, error) {
|
||||
}
|
||||
|
||||
if meta.Key != "" {
|
||||
verificationRequest.Key = meta.Key
|
||||
verificationRequest.ObjectID = meta.ID.String()
|
||||
verificationRequests = append(verificationRequests, verificationRequest)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
verificationRequestCollection := mgr.mongodb.Collection(Collections.VerificationRequest, options.Collection())
|
||||
cursor, err := verificationRequestCollection.Find(nil, bson.M{}, options.Find())
|
||||
if err != nil {
|
||||
log.Println("error getting verification requests:", err)
|
||||
return verificationRequests, err
|
||||
}
|
||||
defer cursor.Close(nil)
|
||||
|
||||
for cursor.Next(nil) {
|
||||
var verificationRequest VerificationRequest
|
||||
err := cursor.Decode(&verificationRequest)
|
||||
if err != nil {
|
||||
return verificationRequests, err
|
||||
}
|
||||
verificationRequests = append(verificationRequests, verificationRequest)
|
||||
}
|
||||
}
|
||||
|
||||
return verificationRequests, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) GetVerificationByToken(token string) (VerificationRequest, error) {
|
||||
var verification VerificationRequest
|
||||
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Where("token = ?", token).First(&verification)
|
||||
|
||||
if result.Error != nil {
|
||||
@@ -133,12 +171,20 @@ func (mgr *manager) GetVerificationByToken(token string) (VerificationRequest, e
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
verificationRequestCollection := mgr.mongodb.Collection(Collections.VerificationRequest, options.Collection())
|
||||
err := verificationRequestCollection.FindOne(nil, bson.M{"token": token}).Decode(&verification)
|
||||
if err != nil {
|
||||
return verification, err
|
||||
}
|
||||
}
|
||||
|
||||
return verification, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) GetVerificationByEmail(email string) (VerificationRequest, error) {
|
||||
var verification VerificationRequest
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Where("email = ?", email).First(&verification)
|
||||
|
||||
if result.Error != nil {
|
||||
@@ -173,11 +219,19 @@ func (mgr *manager) GetVerificationByEmail(email string) (VerificationRequest, e
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
verificationRequestCollection := mgr.mongodb.Collection(Collections.VerificationRequest, options.Collection())
|
||||
err := verificationRequestCollection.FindOne(nil, bson.M{"email": email}).Decode(&verification)
|
||||
if err != nil {
|
||||
return verification, err
|
||||
}
|
||||
}
|
||||
|
||||
return verification, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) DeleteVerificationRequest(verificationRequest VerificationRequest) error {
|
||||
if IsSQL {
|
||||
if IsORMSupported {
|
||||
result := mgr.sqlDB.Delete(&verificationRequest)
|
||||
|
||||
if result.Error != nil {
|
||||
@@ -195,5 +249,14 @@ func (mgr *manager) DeleteVerificationRequest(verificationRequest VerificationRe
|
||||
}
|
||||
}
|
||||
|
||||
if IsMongoDB {
|
||||
verificationRequestCollection := mgr.mongodb.Collection(Collections.VerificationRequest, options.Collection())
|
||||
_, err := verificationRequestCollection.DeleteOne(nil, bson.M{"id": verificationRequest.ID}, options.Delete())
|
||||
if err != nil {
|
||||
log.Println("error deleting verification request::", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@@ -8,6 +8,7 @@ const (
|
||||
Mysql
|
||||
SQLServer
|
||||
Arangodb
|
||||
Mongodb
|
||||
)
|
||||
|
||||
func (d DbType) String() string {
|
||||
@@ -17,5 +18,6 @@ func (d DbType) String() string {
|
||||
"mysql",
|
||||
"sqlserver",
|
||||
"arangodb",
|
||||
"mongodb",
|
||||
}[d]
|
||||
}
|
||||
|
17
server/env/env.go
vendored
17
server/env/env.go
vendored
@@ -87,15 +87,30 @@ func InitEnv() {
|
||||
|
||||
allowedOriginsSplit := strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",")
|
||||
allowedOrigins := []string{}
|
||||
hasWildCard := false
|
||||
|
||||
for _, val := range allowedOriginsSplit {
|
||||
trimVal := strings.TrimSpace(val)
|
||||
if trimVal != "" {
|
||||
allowedOrigins = append(allowedOrigins, trimVal)
|
||||
if trimVal != "*" {
|
||||
host, port := utils.GetHostParts(trimVal)
|
||||
allowedOrigins = append(allowedOrigins, host+":"+port)
|
||||
} else {
|
||||
hasWildCard = true
|
||||
allowedOrigins = append(allowedOrigins, trimVal)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(allowedOrigins) > 1 && hasWildCard {
|
||||
allowedOrigins = []string{"*"}
|
||||
}
|
||||
|
||||
if len(allowedOrigins) == 0 {
|
||||
allowedOrigins = []string{"*"}
|
||||
}
|
||||
|
||||
constants.ALLOWED_ORIGINS = allowedOrigins
|
||||
|
||||
if *ARG_AUTHORIZER_URL != "" {
|
||||
|
@@ -23,6 +23,7 @@ require (
|
||||
github.com/stretchr/testify v1.7.0 // indirect
|
||||
github.com/ugorji/go v1.2.6 // indirect
|
||||
github.com/vektah/gqlparser/v2 v2.1.0
|
||||
go.mongodb.org/mongo-driver v1.8.1 // indirect
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519
|
||||
golang.org/x/net v0.0.0-20210614182718-04defd469f4e // indirect
|
||||
golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914
|
||||
|
@@ -109,6 +109,7 @@ github.com/go-redis/redis/v8 v8.11.0 h1:O1Td0mQ8UFChQ3N9zFQqo6kTU2cJ+/it88gDB+zg
|
||||
github.com/go-redis/redis/v8 v8.11.0/go.mod h1:DLomh7y2e3ggQXQLd1YgmvIfecPJoFl7WU5SOQ/r06M=
|
||||
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
|
||||
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
@@ -144,6 +145,8 @@ github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
@@ -153,6 +156,7 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
@@ -243,6 +247,8 @@ github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/
|
||||
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
|
||||
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
@@ -281,6 +287,7 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ
|
||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
|
||||
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||
github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78=
|
||||
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
@@ -331,6 +338,7 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
github.com/ugorji/go v1.2.6 h1:tGiWC9HENWE2tqYycIqFTNorMmFRVhNwCpDOpWqnk8E=
|
||||
github.com/ugorji/go v1.2.6/go.mod h1:anCg0y61KIhDlPZmnH+so+RQbysYVyDko0IMgJv0Nn0=
|
||||
@@ -341,11 +349,21 @@ github.com/urfave/cli/v2 v2.1.1/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2
|
||||
github.com/vektah/dataloaden v0.2.1-0.20190515034641-a19b9a6e7c9e/go.mod h1:/HUdMve7rvxZma+2ZELQeNh88+003LL7Pf/CZ089j8U=
|
||||
github.com/vektah/gqlparser/v2 v2.1.0 h1:uiKJ+T5HMGGQM2kRKQ8Pxw8+Zq9qhhZhz/lieYvCMns=
|
||||
github.com/vektah/gqlparser/v2 v2.1.0/go.mod h1:SyUiHgLATUR8BiYURfTirrTcGpcE+4XkV2se04Px1Ms=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.0.2 h1:akYIkZ28e6A96dkWNJQu3nmCzH3YfwMPQExUYDaRv7w=
|
||||
github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs=
|
||||
github.com/xdg-go/stringprep v1.0.2 h1:6iq84/ryjjeRmMJwxutI51F2GIPlP5BfTvXHeYjyhBc=
|
||||
github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
|
||||
go.mongodb.org/mongo-driver v1.8.1 h1:OZE4Wni/SJlrcmSIBRYNzunX5TKxjrTS4jKSnA99oKU=
|
||||
go.mongodb.org/mongo-driver v1.8.1/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCuAROlKEPY=
|
||||
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
||||
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
||||
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||
@@ -371,6 +389,7 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.0.0-20201216223049-8b5274cf687f/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
|
||||
@@ -455,6 +474,7 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 h1:SQFwaSi55rU7vdNs9Yr0Z324VNlrF+0wMqRXT4St8ck=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -507,6 +527,7 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
@@ -525,6 +546,7 @@ golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBn
|
||||
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190515012406-7d7faa4812bd/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
|
@@ -49,7 +49,7 @@ func AppHandler() gin.HandlerFunc {
|
||||
stateObj.RedirectURL = strings.TrimSuffix(stateObj.RedirectURL, "/")
|
||||
|
||||
// validate redirect url with allowed origins
|
||||
if !utils.IsValidRedirectURL(stateObj.RedirectURL) {
|
||||
if !utils.IsValidOrigin(stateObj.RedirectURL) {
|
||||
c.JSON(400, gin.H{"error": "invalid redirect url"})
|
||||
return
|
||||
}
|
||||
|
44
server/integration_test/cors_test.go
Normal file
44
server/integration_test/cors_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/env"
|
||||
"github.com/authorizerdev/authorizer/server/middlewares"
|
||||
"github.com/gin-contrib/location"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCors(t *testing.T) {
|
||||
constants.ENV_PATH = "../../.env.local"
|
||||
env.InitEnv()
|
||||
r := gin.Default()
|
||||
r.Use(location.Default())
|
||||
r.Use(middlewares.GinContextToContextMiddleware())
|
||||
r.Use(middlewares.CORSMiddleware())
|
||||
allowedOrigin := "http://localhost:8080" // The allowed origin that you want to check
|
||||
notAllowedOrigin := "http://myapp.com"
|
||||
|
||||
server := httptest.NewServer(r)
|
||||
defer server.Close()
|
||||
|
||||
client := &http.Client{}
|
||||
req, _ := http.NewRequest(
|
||||
"GET",
|
||||
"http://"+server.Listener.Addr().String()+"/api",
|
||||
nil,
|
||||
)
|
||||
req.Header.Add("Origin", allowedOrigin)
|
||||
|
||||
get, _ := client.Do(req)
|
||||
|
||||
// You should get your origin (or a * depending on your config) if the
|
||||
// passed origin is allowed.
|
||||
o := get.Header.Get("Access-Control-Allow-Origin")
|
||||
assert.NotEqual(t, o, notAllowedOrigin, "Origins should not match")
|
||||
assert.Equal(t, o, allowedOrigin, "Origins don't match")
|
||||
}
|
@@ -1,13 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/db"
|
||||
"github.com/authorizerdev/authorizer/server/env"
|
||||
"github.com/authorizerdev/authorizer/server/handlers"
|
||||
"github.com/authorizerdev/authorizer/server/middlewares"
|
||||
"github.com/authorizerdev/authorizer/server/oauth"
|
||||
"github.com/authorizerdev/authorizer/server/session"
|
||||
"github.com/authorizerdev/authorizer/server/utils"
|
||||
@@ -15,39 +12,6 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GinContextToContextMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if constants.AUTHORIZER_URL == "" {
|
||||
url := location.Get(c)
|
||||
constants.AUTHORIZER_URL = url.Scheme + "://" + c.Request.Host
|
||||
log.Println("=> authorizer url:", constants.AUTHORIZER_URL)
|
||||
}
|
||||
ctx := context.WithValue(c.Request.Context(), "GinContextKey", c)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO use allowed origins for cors origin
|
||||
// TODO throw error if url is not allowed
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
origin := c.Request.Header.Get("Origin")
|
||||
constants.APP_URL = origin
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
env.InitEnv()
|
||||
db.InitDB()
|
||||
@@ -57,8 +21,8 @@ func main() {
|
||||
|
||||
r := gin.Default()
|
||||
r.Use(location.Default())
|
||||
r.Use(GinContextToContextMiddleware())
|
||||
r.Use(CORSMiddleware())
|
||||
r.Use(middlewares.GinContextToContextMiddleware())
|
||||
r.Use(middlewares.CORSMiddleware())
|
||||
|
||||
r.GET("/", handlers.PlaygroundHandler())
|
||||
r.POST("/graphql", handlers.GraphqlHandler())
|
||||
|
23
server/middlewares/context.go
Normal file
23
server/middlewares/context.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/gin-contrib/location"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GinContextToContextMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if constants.AUTHORIZER_URL == "" {
|
||||
url := location.Get(c)
|
||||
constants.AUTHORIZER_URL = url.Scheme + "://" + c.Request.Host
|
||||
log.Println("=> authorizer url:", constants.AUTHORIZER_URL)
|
||||
}
|
||||
ctx := context.WithValue(c.Request.Context(), "GinContextKey", c)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
29
server/middlewares/cors.go
Normal file
29
server/middlewares/cors.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
origin := c.Request.Header.Get("Origin")
|
||||
constants.APP_URL = origin
|
||||
|
||||
if utils.IsValidOrigin(origin) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
}
|
||||
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
@@ -26,7 +26,7 @@ func Signup(ctx context.Context, params model.SignUpInput) (*model.AuthResponse,
|
||||
return res, fmt.Errorf(`basic authentication is disabled for this instance`)
|
||||
}
|
||||
if params.ConfirmPassword != params.Password {
|
||||
return res, fmt.Errorf(`passowrd and confirm password does not match`)
|
||||
return res, fmt.Errorf(`password and confirm password does not match`)
|
||||
}
|
||||
|
||||
params.Email = strings.ToLower(params.Email)
|
||||
@@ -56,8 +56,11 @@ func Signup(ctx context.Context, params model.SignUpInput) (*model.AuthResponse,
|
||||
|
||||
if existingUser.EmailVerifiedAt > 0 {
|
||||
// email is verified
|
||||
return res, fmt.Errorf(`you have already signed up. Please login`)
|
||||
return res, fmt.Errorf(`%s has already signed up`, params.Email)
|
||||
} else if existingUser.ID != "" && existingUser.EmailVerifiedAt <= 0 {
|
||||
return res, fmt.Errorf("%s has already signed up. please complete the email verification process or reset the password", params.Email)
|
||||
}
|
||||
|
||||
user := db.User{
|
||||
Email: params.Email,
|
||||
}
|
||||
|
@@ -10,7 +10,7 @@ import (
|
||||
func SetCookie(gc *gin.Context, token string) {
|
||||
secure := true
|
||||
httpOnly := true
|
||||
host := GetHostName(constants.AUTHORIZER_URL)
|
||||
host, _ := GetHostParts(constants.AUTHORIZER_URL)
|
||||
domain := GetDomainName(constants.AUTHORIZER_URL)
|
||||
if domain != "localhost" {
|
||||
domain = "." + domain
|
||||
@@ -37,7 +37,7 @@ func DeleteCookie(gc *gin.Context) {
|
||||
secure := true
|
||||
httpOnly := true
|
||||
|
||||
host := GetDomainName(constants.AUTHORIZER_URL)
|
||||
host, _ := GetHostParts(constants.AUTHORIZER_URL)
|
||||
domain := GetDomainName(constants.AUTHORIZER_URL)
|
||||
if domain != "localhost" {
|
||||
domain = "." + domain
|
||||
|
@@ -5,21 +5,32 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GetHostName function to get hostname
|
||||
func GetHostName(auth_url string) string {
|
||||
u, err := url.Parse(auth_url)
|
||||
// GetHostName function returns hostname and port
|
||||
func GetHostParts(uri string) (string, string) {
|
||||
tempURI := uri
|
||||
if !strings.HasPrefix(tempURI, "http") && strings.HasPrefix(tempURI, "https") {
|
||||
tempURI = "https://" + tempURI
|
||||
}
|
||||
|
||||
u, err := url.Parse(tempURI)
|
||||
if err != nil {
|
||||
return `localhost`
|
||||
return "localhost", "8080"
|
||||
}
|
||||
|
||||
host := u.Hostname()
|
||||
port := u.Port()
|
||||
|
||||
return host
|
||||
return host, port
|
||||
}
|
||||
|
||||
// GetDomainName function to get domain name
|
||||
func GetDomainName(auth_url string) string {
|
||||
u, err := url.Parse(auth_url)
|
||||
func GetDomainName(uri string) string {
|
||||
tempURI := uri
|
||||
if !strings.HasPrefix(tempURI, "http") && strings.HasPrefix(tempURI, "https") {
|
||||
tempURI = "https://" + tempURI
|
||||
}
|
||||
|
||||
u, err := url.Parse(tempURI)
|
||||
if err != nil {
|
||||
return `localhost`
|
||||
}
|
||||
|
@@ -7,12 +7,13 @@ import (
|
||||
)
|
||||
|
||||
func TestGetHostName(t *testing.T) {
|
||||
authorizer_url := "http://test.herokuapp.com"
|
||||
authorizer_url := "http://test.herokuapp.com:80"
|
||||
|
||||
got := GetHostName(authorizer_url)
|
||||
want := "test.herokuapp.com"
|
||||
host, port := GetHostParts(authorizer_url)
|
||||
expectedHost := "test.herokuapp.com"
|
||||
|
||||
assert.Equal(t, got, want, "hostname should be equal")
|
||||
assert.Equal(t, host, expectedHost, "hostname should be equal")
|
||||
assert.Equal(t, port, "80", "port should be 80")
|
||||
}
|
||||
|
||||
func TestGetDomainName(t *testing.T) {
|
||||
|
@@ -2,6 +2,7 @@ package utils
|
||||
|
||||
import (
|
||||
"net/mail"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
@@ -13,16 +14,32 @@ func IsValidEmail(email string) bool {
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func IsValidRedirectURL(url string) bool {
|
||||
func IsValidOrigin(url string) bool {
|
||||
if len(constants.ALLOWED_ORIGINS) == 1 && constants.ALLOWED_ORIGINS[0] == "*" {
|
||||
return true
|
||||
}
|
||||
|
||||
hasValidURL := false
|
||||
urlDomain := GetDomainName(url)
|
||||
hostName, port := GetHostParts(url)
|
||||
currentOrigin := hostName + ":" + port
|
||||
|
||||
for _, val := range constants.ALLOWED_ORIGINS {
|
||||
if strings.Contains(val, urlDomain) {
|
||||
for _, origin := range constants.ALLOWED_ORIGINS {
|
||||
replacedString := origin
|
||||
// if has regex whitelisted domains
|
||||
if strings.Contains(origin, "*") {
|
||||
replacedString = strings.Replace(origin, ".", "\\.", -1)
|
||||
replacedString = strings.Replace(replacedString, "*", ".*", -1)
|
||||
|
||||
if strings.HasPrefix(replacedString, ".*") {
|
||||
replacedString += "\\b"
|
||||
}
|
||||
|
||||
if strings.HasSuffix(replacedString, ".*") {
|
||||
replacedString = "\\b" + replacedString
|
||||
}
|
||||
}
|
||||
|
||||
if matched, _ := regexp.MatchString(replacedString, currentOrigin); matched {
|
||||
hasValidURL = true
|
||||
break
|
||||
}
|
||||
|
@@ -3,6 +3,7 @@ package utils
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -15,3 +16,19 @@ func TestIsValidEmail(t *testing.T) {
|
||||
assert.False(t, IsValidEmail(invalidEmail1), "it should be invalid email")
|
||||
assert.False(t, IsValidEmail(invalidEmail2), "it should be invalid email")
|
||||
}
|
||||
|
||||
func TestIsValidOrigin(t *testing.T) {
|
||||
// don't use portocal(http/https) for ALLOWED_ORIGINS while testing,
|
||||
// as we trim them off while running the main function
|
||||
constants.ALLOWED_ORIGINS = []string{"localhost:8080", "*.google.com", "*.google.in", "*abc.*"}
|
||||
|
||||
assert.False(t, IsValidOrigin("http://myapp.com"), "it should be invalid origin")
|
||||
assert.False(t, IsValidOrigin("http://appgoogle.com"), "it should be invalid origin")
|
||||
assert.True(t, IsValidOrigin("http://app.google.com"), "it should be valid origin")
|
||||
assert.False(t, IsValidOrigin("http://app.google.ind"), "it should be invalid origin")
|
||||
assert.True(t, IsValidOrigin("http://app.google.in"), "it should be valid origin")
|
||||
assert.True(t, IsValidOrigin("http://xyx.abc.com"), "it should be valid origin")
|
||||
assert.True(t, IsValidOrigin("http://xyx.abc.in"), "it should be valid origin")
|
||||
assert.True(t, IsValidOrigin("http://xyxabc.in"), "it should be valid origin")
|
||||
assert.True(t, IsValidOrigin("http://localhost:8080"), "it should be valid origin")
|
||||
}
|
||||
|
Reference in New Issue
Block a user