@prosopo/client-example-server 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/.env.development +9 -0
  2. package/README.md +6 -0
  3. package/dist/app.d.ts +3 -0
  4. package/dist/app.d.ts.map +1 -0
  5. package/dist/app.js +56 -0
  6. package/dist/app.js.map +1 -0
  7. package/dist/bundle/nodejs-polars.linux-x64-gnu.node +0 -0
  8. package/dist/bundle/prosopo_client_example_server.app.bundle.js +289803 -0
  9. package/dist/controllers/auth.d.ts +7 -0
  10. package/dist/controllers/auth.d.ts.map +1 -0
  11. package/dist/controllers/auth.js +125 -0
  12. package/dist/controllers/auth.js.map +1 -0
  13. package/dist/models/user.d.ts +15 -0
  14. package/dist/models/user.d.ts.map +1 -0
  15. package/dist/models/user.js +32 -0
  16. package/dist/models/user.js.map +1 -0
  17. package/dist/prosopo.config.d.ts +30 -0
  18. package/dist/prosopo.config.d.ts.map +1 -0
  19. package/dist/prosopo.config.js +57 -0
  20. package/dist/prosopo.config.js.map +1 -0
  21. package/dist/routes/routes.d.ts +6 -0
  22. package/dist/routes/routes.d.ts.map +1 -0
  23. package/dist/routes/routes.js +18 -0
  24. package/dist/routes/routes.js.map +1 -0
  25. package/dist/utils/connection.d.ts +4 -0
  26. package/dist/utils/connection.d.ts.map +1 -0
  27. package/dist/utils/connection.js +26 -0
  28. package/dist/utils/connection.js.map +1 -0
  29. package/dist/utils/database.d.ts +3 -0
  30. package/dist/utils/database.d.ts.map +1 -0
  31. package/dist/utils/database.js +21 -0
  32. package/dist/utils/database.js.map +1 -0
  33. package/env.development +9 -0
  34. package/package.json +49 -0
  35. package/src/app.ts +84 -0
  36. package/src/controllers/auth.ts +134 -0
  37. package/src/models/user.ts +41 -0
  38. package/src/prosopo.config.ts +60 -0
  39. package/src/routes/routes.ts +39 -0
  40. package/src/utils/connection.ts +26 -0
  41. package/src/utils/database.ts +20 -0
  42. package/tsconfig.json +50 -0
  43. package/tsconfig.tsbuildinfo +1 -0
  44. package/tsconfig.webpack.json +14 -0
  45. package/vite.config.ts +26 -0
@@ -0,0 +1,134 @@
1
+ // Copyright 2021-2023 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ import { ApiParams } from '@prosopo/types'
15
+ import { Connection } from 'mongoose'
16
+ import { ProcaptchaResponse } from '@prosopo/types'
17
+ import { ProsopoServer } from '@prosopo/server'
18
+ import { UserInterface } from '../models/user'
19
+ import { blake2b } from '@noble/hashes/blake2b'
20
+ import { randomAsHex } from '@polkadot/util-crypto'
21
+ import { u8aToHex } from '@polkadot/util'
22
+ import { z } from 'zod'
23
+ import jwt from 'jsonwebtoken'
24
+
25
+ const SubscribeBodySpec = ProcaptchaResponse.merge(
26
+ z.object({
27
+ email: z.string().email(),
28
+ password: z.string(),
29
+ })
30
+ )
31
+
32
+ function hashPassword(password: string): string {
33
+ return u8aToHex(blake2b(password))
34
+ }
35
+
36
+ const signup = async (mongoose: Connection, prosopoServer: ProsopoServer, req, res, next) => {
37
+ try {
38
+ const User = mongoose.model<UserInterface>('User')
39
+ // checks if email exists
40
+ const dbUser = await User.findOne({
41
+ email: req.body.email,
42
+ })
43
+ const payload = SubscribeBodySpec.parse(req.body)
44
+ await prosopoServer.isReady()
45
+ if (dbUser) {
46
+ return res.status(409).json({ message: 'email already exists' })
47
+ }
48
+
49
+ if (await prosopoServer.isVerified(payload[ApiParams.procaptchaResponse])) {
50
+ // salt
51
+ const salt = randomAsHex(32)
52
+ // !!!DUMMY CODE!!! - Do not use in production. Use bcrypt or similar for password hashing.
53
+ const passwordHash = hashPassword(`${req.body.password}${salt}`)
54
+
55
+ if (passwordHash) {
56
+ return User.create({
57
+ email: req.body.email,
58
+ name: req.body.name,
59
+ password: passwordHash,
60
+ salt: salt,
61
+ })
62
+ .then(() => {
63
+ res.status(200).json({ message: 'user created' })
64
+ })
65
+ .catch((err) => {
66
+ console.log(err)
67
+ res.status(502).json({ message: 'error while creating the user' })
68
+ })
69
+ }
70
+ } else {
71
+ res.status(401).json({ message: 'user has not completed a captcha' })
72
+ }
73
+ } catch (err) {
74
+ console.error('error', err)
75
+ res.status(500).json({ message: err.message || 'internal server error' })
76
+ }
77
+ }
78
+
79
+ const login = async (mongoose: Connection, prosopoServer: ProsopoServer, req, res) => {
80
+ const User = mongoose.model<UserInterface>('User')
81
+ await prosopoServer.isReady()
82
+ // checks if email exists
83
+ await User.findOne({
84
+ email: req.body.email,
85
+ })
86
+ .then(async (dbUser) => {
87
+ if (!dbUser) {
88
+ return res.status(404).json({ message: 'user not found' })
89
+ } else {
90
+ const payload = SubscribeBodySpec.parse(req.body)
91
+
92
+ if (await prosopoServer.isVerified(payload[ApiParams.procaptchaResponse])) {
93
+ // password hash
94
+ // !!!DUMMY CODE!!! - Do not use in production. Use bcrypt or similar for password hashing.
95
+ const passwordHash = hashPassword(`${req.body.password}${dbUser.salt}`)
96
+ if (passwordHash !== dbUser.password) {
97
+ // password doesnt match
98
+ res.status(401).json({ message: 'invalid credentials' })
99
+ } else {
100
+ // password match
101
+ const token = jwt.sign({ email: req.body.email }, 'secret', { expiresIn: '1h' })
102
+ res.status(200).json({ message: 'user logged in', token: token })
103
+ }
104
+ }
105
+ }
106
+ })
107
+ .catch((err) => {
108
+ console.error('error', err)
109
+ res.status(500).json({ message: err.message || 'internal server error' })
110
+ })
111
+ }
112
+
113
+ const isAuth = (req, res) => {
114
+ const authHeader = req.get('Authorization')
115
+ if (!authHeader) {
116
+ return res.status(401).json({ message: 'not authenticated' })
117
+ }
118
+
119
+ const token = authHeader.split(' ')[1]
120
+ let decodedToken
121
+ try {
122
+ decodedToken = jwt.verify(token, 'secret')
123
+ } catch (err) {
124
+ return res.status(500).json({ message: err.message || 'could not decode the token' })
125
+ }
126
+
127
+ if (!decodedToken) {
128
+ res.status(401).json({ message: 'unauthorized' })
129
+ } else {
130
+ res.status(200).json({ message: 'here is your resource' })
131
+ }
132
+ }
133
+
134
+ export { signup, login, isAuth }
@@ -0,0 +1,41 @@
1
+ // Copyright 2021-2023 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ import mongoose, { Schema } from 'mongoose'
15
+
16
+ export interface UserInterface {
17
+ id: number
18
+ email: string
19
+ name: string
20
+ password: string
21
+ salt: string
22
+ }
23
+
24
+ const UserSchema = new Schema<UserInterface>({
25
+ email: {
26
+ type: mongoose.SchemaTypes.String,
27
+ required: true,
28
+ },
29
+ name: {
30
+ type: mongoose.SchemaTypes.String,
31
+ },
32
+ password: {
33
+ type: mongoose.SchemaTypes.String,
34
+ required: true,
35
+ },
36
+ id: {
37
+ type: mongoose.SchemaTypes.Number,
38
+ },
39
+ })
40
+
41
+ export default UserSchema
@@ -0,0 +1,60 @@
1
+ // Copyright 2021-2022 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ // import {ProsopoConfig} from './types';
15
+
16
+ import { EnvironmentTypesSchema, ProsopoServerConfig } from '@prosopo/types'
17
+ import { LogLevelSchema } from '@prosopo/common'
18
+
19
+ export default () =>
20
+ ({
21
+ logLevel: process.env.LOG_LEVEL || LogLevelSchema.enum.Debug,
22
+ defaultEnvironment: process.env.DEFAULT_ENVIRONMENT || EnvironmentTypesSchema.enum.development, // enviromental variables
23
+ web2: process.env.REACT_APP_WEB2 || true,
24
+ serverUrl:
25
+ process.env.REACT_APP_SERVER_URL && process.env.REACT_APP_SERVER_PORT
26
+ ? `${process.env.REACT_APP_SERVER_URL}:${process.env.REACT_APP_SERVER_PORT}`
27
+ : 'http://localhost:9228',
28
+ solutionThreshold: process.env.REACT_APP_SOLUTION_THRESHOLD || 0.5,
29
+ dappName: process.env.REACT_APP_DAPP_NAME || 'client-example-server',
30
+ account: {
31
+ password: '',
32
+ address: process.env.REACT_APP_SERVER_ACCOUNT_ADDRESS || '',
33
+ },
34
+ networks: {
35
+ development: {
36
+ endpoint: process.env.REACT_APP_SUBSTRATE_NODE_URL || 'ws://localhost:9944',
37
+ contract: {
38
+ address: process.env.REACT_APP_PROSOPO_CONTRACT_ADDRESS,
39
+ name: 'prosopo',
40
+ },
41
+ dappAccount: {
42
+ address: process.env.REACT_APP_DAPP_SITE_KEY,
43
+ name: 'dapp',
44
+ },
45
+ accounts: ['//Alice', '//Bob', '//Charlie', '//Dave', '//Eve', '//Ferdie'],
46
+ },
47
+ shiden: {
48
+ endpoint: 'wss://shiden.public.blastapi.io',
49
+ contract: {
50
+ address: process.env.REACT_APP_PROSOPO_CONTRACT_ADDRESS,
51
+ name: 'prosopo',
52
+ },
53
+ dappAccount: {
54
+ address: process.env.REACT_APP_DAPP_SITE_KEY,
55
+ name: 'dapp',
56
+ },
57
+ accounts: [],
58
+ },
59
+ },
60
+ } as ProsopoServerConfig)
@@ -0,0 +1,39 @@
1
+ // Copyright 2021-2023 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ import { Connection } from 'mongoose'
15
+ import { ProsopoServer } from '@prosopo/server'
16
+ import { isAuth, login, signup } from '../controllers/auth'
17
+ import express from 'express'
18
+
19
+ const router = express.Router()
20
+
21
+ function getRoutes(mongoose: Connection, prosopoServer: ProsopoServer): express.Router {
22
+ router.post('/login', login.bind(null, mongoose, prosopoServer))
23
+
24
+ router.post('/signup', signup.bind(null, mongoose, prosopoServer))
25
+
26
+ router.get('/private', isAuth)
27
+
28
+ router.get('/public', (req, res) => {
29
+ res.status(200).json({ message: 'here is your public resource' })
30
+ })
31
+
32
+ // will match any other path
33
+ router.use('/', (req, res) => {
34
+ res.status(404).json({ error: 'page not found' })
35
+ })
36
+ return router
37
+ }
38
+
39
+ export default getRoutes
@@ -0,0 +1,26 @@
1
+ // Copyright 2021-2023 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ import { AutoIncrementID, AutoIncrementIDOptions } from '@typegoose/auto-increment'
15
+ import UserSchema from '../models/user'
16
+ import mongoose, { Connection } from 'mongoose'
17
+
18
+ function connectionFactory(uri: string): Connection {
19
+ const conn = mongoose.createConnection(uri)
20
+ if (!conn.models.user) {
21
+ UserSchema.plugin(AutoIncrementID, { field: 'id' } as AutoIncrementIDOptions)
22
+ conn.model('User', UserSchema)
23
+ }
24
+ return conn
25
+ }
26
+ export default connectionFactory
@@ -0,0 +1,20 @@
1
+ // Copyright 2021-2023 Prosopo (UK) Ltd.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ import { MongoMemoryServer } from 'mongodb-memory-server'
15
+ export async function memoryServerSetup(): Promise<string> {
16
+ const mongod = MongoMemoryServer.create()
17
+ const memoryServer = await mongod
18
+ return memoryServer.getUri()
19
+ }
20
+ export default memoryServerSetup
package/tsconfig.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "extends": "../../tsconfig.build.json",
3
+ "compilerOptions": {
4
+ "target": "esnext",
5
+ "rootDir": "./src",
6
+ "outDir": "./dist",
7
+ "lib": [
8
+ "dom",
9
+ "dom.iterable",
10
+ "esnext"
11
+ ],
12
+ "allowJs": true,
13
+ "skipLibCheck": true,
14
+ "esModuleInterop": true,
15
+ "allowSyntheticDefaultImports": true,
16
+ // "strict": true,
17
+ "forceConsistentCasingInFileNames": true,
18
+ "noFallthroughCasesInSwitch": true,
19
+ "moduleResolution": "node",
20
+ "resolveJsonModule": true,
21
+ // "isolatedModules": true,
22
+ // "noEmit": true,
23
+ "jsx": "react-jsx"
24
+ },
25
+ "include": [
26
+ "./src/**/*.ts",
27
+ "./src/**/*.js"
28
+ ],
29
+ "exclude": ["node_modules", "dist"],
30
+ "references": [
31
+ {
32
+ "path": "../../packages/api"
33
+ },
34
+ {
35
+ "path": "../../packages/cli"
36
+ },
37
+ {
38
+ "path": "../../packages/contract"
39
+ },
40
+ {
41
+ "path": "../../packages/procaptcha"
42
+ },
43
+ {
44
+ "path": "../../packages/server"
45
+ },
46
+ {
47
+ "path": "../../packages/types"
48
+ }
49
+ ]
50
+ }