@prosopo/client-example-server 0.2.11 → 0.2.13

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.
@@ -0,0 +1,9 @@
1
+ REACT_APP_API_PATH_PREFIX=/v1/prosopo
2
+ REACT_APP_DAPP_SITE_KEY=
3
+ REACT_APP_SUBSTRATE_NODE_URL=ws://localhost:9944
4
+ REACT_APP_PROSOPO_CONTRACT_ADDRESS=
5
+ REACT_APP_WEB2=true
6
+ REACT_APP_SERVER_URL=https://localhost
7
+ REACT_APP_SERVER_MNEMONIC=//Bob
8
+ REACT_APP_SERVER_ACCOUNT_ADDRESS=
9
+ REACT_APP_SERVER_PORT=9228
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prosopo/client-example-server",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "description": "Backend for client-example",
5
5
  "main": "dist/app.js",
6
6
  "type": "module",
@@ -30,15 +30,14 @@
30
30
  "homepage": "https://github.com/prosopo/client-example-server#readme",
31
31
  "dependencies": {
32
32
  "@noble/hashes": "^1.3.1",
33
- "@polkadot/util": "12.3.2",
34
- "@polkadot/util-crypto": "12.3.2",
35
- "@prosopo/api": "0.2.11",
36
- "@prosopo/contract": "0.2.11",
37
- "@prosopo/procaptcha": "0.2.11",
38
- "@prosopo/server": "0.2.11",
39
- "@prosopo/types": "0.2.11",
33
+ "@polkadot/util": "12.5.1",
34
+ "@polkadot/util-crypto": "12.5.1",
35
+ "@prosopo/api": "0.2.13",
36
+ "@prosopo/contract": "0.2.13",
37
+ "@prosopo/procaptcha": "0.2.13",
38
+ "@prosopo/server": "0.2.13",
39
+ "@prosopo/types": "0.2.13",
40
40
  "@typegoose/auto-increment": "3.3.0",
41
- "axios": "^1.5.0",
42
41
  "cors": "^2.8.5",
43
42
  "jsonwebtoken": "^9.0.0",
44
43
  "mongoose": "^7.3.3",
@@ -52,6 +51,6 @@
52
51
  "tslib": "2.6.2",
53
52
  "typescript": "5.1.6",
54
53
  "vite": "^4.4.9",
55
- "@prosopo/config": "0.2.11"
54
+ "@prosopo/config": "0.2.13"
56
55
  }
57
56
  }
package/src/app.ts ADDED
@@ -0,0 +1,80 @@
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 { ProsopoServer, getServerConfig } from '@prosopo/server'
15
+ import { getPair } from '@prosopo/contract'
16
+ import connectionFactory from './utils/connection.js'
17
+ import cors from 'cors'
18
+ import dotenv from 'dotenv'
19
+ import express from 'express'
20
+ import memoryServerSetup from './utils/database.js'
21
+ import path from 'path'
22
+ import routesFactory from './routes/routes.js'
23
+
24
+ export function loadEnv() {
25
+ dotenv.config({ path: getEnvFile() })
26
+ }
27
+
28
+ export function getEnvFile(filename = '.env', filepath = './') {
29
+ const env = process.env.NODE_ENV || 'development'
30
+ return path.join(filepath, `${filename}.${env}`)
31
+ }
32
+
33
+ async function main() {
34
+ loadEnv()
35
+
36
+ const app = express()
37
+
38
+ app.use(cors({ origin: true, credentials: true }))
39
+
40
+ app.use(express.urlencoded({ extended: true }))
41
+
42
+ app.use(express.json())
43
+
44
+ app.use((_, res, next) => {
45
+ res.setHeader('Access-Control-Allow-Origin', '*')
46
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE')
47
+ res.setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization')
48
+ next()
49
+ })
50
+
51
+ app.options('/*', (_, res) => {
52
+ res.sendStatus(200)
53
+ })
54
+
55
+ const uri = await memoryServerSetup()
56
+ console.log('mongo uri', uri)
57
+ const mongoose = connectionFactory(uri)
58
+ if (!process.env.REACT_APP_SERVER_MNEMONIC) {
59
+ throw new Error('No mnemonic found')
60
+ }
61
+
62
+ const config = getServerConfig()
63
+
64
+ console.log('config', config)
65
+ const pair = await getPair(config.networks[config.defaultNetwork], process.env.REACT_APP_SERVER_MNEMONIC)
66
+ const prosopoServer = new ProsopoServer(config, pair)
67
+
68
+ app.use(routesFactory(mongoose, prosopoServer))
69
+
70
+ app.listen(process.env.REACT_APP_SERVER_PORT)
71
+ }
72
+
73
+ main()
74
+ .then(() => {
75
+ console.log('Server started')
76
+ })
77
+ .catch((err) => {
78
+ console.log(err)
79
+ process.exit()
80
+ })
@@ -0,0 +1,142 @@
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 { NextFunction, Request, Response } from 'express'
17
+ import { ProcaptchaResponse } from '@prosopo/types'
18
+ import { ProsopoServer } from '@prosopo/server'
19
+ import { UserInterface } from '../models/user.js'
20
+ import { at } from '@prosopo/util'
21
+ import { blake2b } from '@noble/hashes/blake2b'
22
+ import { randomAsHex } from '@polkadot/util-crypto'
23
+ import { u8aToHex } from '@polkadot/util'
24
+ import { z } from 'zod'
25
+ import jwt from 'jsonwebtoken'
26
+
27
+ const SubscribeBodySpec = ProcaptchaResponse.merge(
28
+ z.object({
29
+ email: z.string().email(),
30
+ password: z.string(),
31
+ })
32
+ )
33
+
34
+ function hashPassword(password: string): string {
35
+ return u8aToHex(blake2b(password))
36
+ }
37
+
38
+ const signup = async (
39
+ mongoose: Connection,
40
+ prosopoServer: ProsopoServer,
41
+ req: Request,
42
+ res: Response,
43
+ next: NextFunction
44
+ ) => {
45
+ try {
46
+ const User = mongoose.model<UserInterface>('User')
47
+ // checks if email exists
48
+ const dbUser = await User.findOne({
49
+ email: req.body.email,
50
+ })
51
+ const payload = SubscribeBodySpec.parse(req.body)
52
+ await prosopoServer.isReady()
53
+ if (dbUser) {
54
+ return res.status(409).json({ message: 'email already exists' })
55
+ }
56
+
57
+ if (await prosopoServer.isVerified(payload[ApiParams.procaptchaResponse])) {
58
+ // salt
59
+ const salt = randomAsHex(32)
60
+ // !!!DUMMY CODE!!! - Do not use in production. Use bcrypt or similar for password hashing.
61
+ const passwordHash = hashPassword(`${req.body.password}${salt}`)
62
+
63
+ if (passwordHash) {
64
+ return User.create({
65
+ email: req.body.email,
66
+ name: req.body.name,
67
+ password: passwordHash,
68
+ salt: salt,
69
+ })
70
+ .then(() => {
71
+ res.status(200).json({ message: 'user created' })
72
+ })
73
+ .catch((err) => {
74
+ console.log(err)
75
+ res.status(502).json({ message: 'error while creating the user' })
76
+ })
77
+ }
78
+ } else {
79
+ res.status(401).json({ message: 'user has not completed a captcha' })
80
+ }
81
+ } catch (err) {
82
+ console.error('error', err)
83
+ res.status(500).json({ message: (err as Error).message || 'internal server error' })
84
+ }
85
+ }
86
+
87
+ const login = async (mongoose: Connection, prosopoServer: ProsopoServer, req: Request, res: Response) => {
88
+ const User = mongoose.model<UserInterface>('User')
89
+ await prosopoServer.isReady()
90
+ // checks if email exists
91
+ await User.findOne({
92
+ email: req.body.email,
93
+ })
94
+ .then(async (dbUser) => {
95
+ if (!dbUser) {
96
+ res.status(404).json({ message: 'user not found' })
97
+ } else {
98
+ const payload = SubscribeBodySpec.parse(req.body)
99
+
100
+ if (await prosopoServer.isVerified(payload[ApiParams.procaptchaResponse])) {
101
+ // password hash
102
+ // !!!DUMMY CODE!!! - Do not use in production. Use bcrypt or similar for password hashing.
103
+ const passwordHash = hashPassword(`${req.body.password}${dbUser.salt}`)
104
+ if (passwordHash !== dbUser.password) {
105
+ // password doesnt match
106
+ res.status(401).json({ message: 'invalid credentials' })
107
+ } else {
108
+ // password match
109
+ const token = jwt.sign({ email: req.body.email }, 'secret', { expiresIn: '1h' })
110
+ res.status(200).json({ message: 'user logged in', token: token })
111
+ }
112
+ }
113
+ }
114
+ })
115
+ .catch((err) => {
116
+ console.error('error', err)
117
+ res.status(500).json({ message: err.message || 'internal server error' })
118
+ })
119
+ }
120
+
121
+ const isAuth = (req: Request, res: Response) => {
122
+ const authHeader = req.get('Authorization') || ''
123
+ if (!authHeader) {
124
+ res.status(401).json({ message: 'not authenticated' })
125
+ }
126
+
127
+ const token = at(authHeader.split(' '), 1)
128
+ let decodedToken
129
+ try {
130
+ decodedToken = jwt.verify(token, 'secret')
131
+ } catch (err) {
132
+ res.status(500).json({ message: (err as Error).message || 'could not decode the token' })
133
+ }
134
+
135
+ if (!decodedToken) {
136
+ res.status(401).json({ message: 'unauthorized' })
137
+ } else {
138
+ res.status(200).json({ message: 'here is your resource' })
139
+ }
140
+ }
141
+
142
+ 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,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.js'
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.js'
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,29 @@
1
+ {
2
+ "extends": "../../tsconfig.esm.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "./dist",
6
+ "lib": ["dom", "dom.iterable", "esnext"]
7
+ },
8
+ "include": ["src", "src/**/*.json"],
9
+ "references": [
10
+ {
11
+ "path": "../../packages/api"
12
+ },
13
+ {
14
+ "path": "../../packages/cli"
15
+ },
16
+ {
17
+ "path": "../../packages/contract"
18
+ },
19
+ {
20
+ "path": "../../packages/procaptcha"
21
+ },
22
+ {
23
+ "path": "../../packages/server"
24
+ },
25
+ {
26
+ "path": "../../packages/types"
27
+ }
28
+ ]
29
+ }