Kaynağa Gözat

:tada: start over

neo
toj 2 yıl önce
ebeveyn
işleme
f55b1147a3
100 değiştirilmiş dosya ile 18 ekleme ve 350069 silme
  1. 0
    30
      backend/db/data-generator/classes.js
  2. 0
    46
      backend/db/data-generator/config.json
  3. 0
    197
      backend/db/data-generator/generate.ipynb
  4. 0
    187
      backend/db/data-generator/index.js
  5. 0
    230
      backend/db/data-generator/lorem.js
  6. 0
    760
      backend/db/data-generator/mock.js
  7. 0
    109
      backend/db/data-generator/random.js
  8. 0
    3
      backend/db/dataSort.js
  9. 0
    2519
      backend/db/generated/prescore_matrix.json
  10. 1
    1
      backend/db/knex.js
  11. 0
    0
      backend/db/migrations/20210524105357_users.js
  12. 0
    10
      backend/db/migrations/20210527173933_create_profiles_table.js
  13. 0
    16
      backend/db/migrations/20210527174416_create_response_keys_table.js
  14. 0
    12
      backend/db/migrations/20210527174422_create_responses_table.js
  15. 0
    11
      backend/db/migrations/20210527174434_create_groupings_table.js
  16. 0
    14
      backend/db/migrations/20210527174440_create_memberships_table.js
  17. 0
    12
      backend/db/migrations/20210527174448_create_messages_table.js
  18. 0
    14
      backend/db/migrations/20210929163630_zipcodes.js
  19. 0
    12
      backend/db/migrations/20211003195015_create_match_queues_table.js
  20. 0
    16
      backend/db/migrations/20220313230903_create_scores_table.js
  21. 0
    13
      backend/db/migrations/20220313233557_create_aspects_table.js
  22. 0
    12
      backend/db/migrations/20220403111017_create_tag_descriptions_table.js
  23. 0
    13
      backend/db/migrations/20220403111037_create_tag_associations_table.js
  24. 0
    13
      backend/db/migrations/20220403111101_create_user_passwords_table.js
  25. 0
    12
      backend/db/migrations/20220403112041_create_blocked_profiles_table.js
  26. 0
    12
      backend/db/migrations/20220901171733_user_authentication.js
  27. 0
    30
      backend/db/seeds/01-users.js
  28. 0
    31
      backend/db/seeds/02-profiles.js
  29. 0
    24
      backend/db/seeds/03-response_keys.js
  30. 0
    35
      backend/db/seeds/04-responses.js
  31. 0
    11
      backend/db/seeds/05-memberships.js
  32. 0
    11
      backend/db/seeds/06-groupings.js
  33. 0
    11
      backend/db/seeds/07-messages.js
  34. 0
    11
      backend/db/seeds/08-zipcodes.js
  35. 0
    10
      backend/db/seeds/09-match_queues.js
  36. 0
    29
      backend/db/seeds/10-scores.js
  37. 0
    25
      backend/db/seeds/11-aspects.js
  38. 0
    11
      backend/db/seeds/12-tags.js
  39. 0
    11
      backend/db/seeds/13-tag_associations.js
  40. 0
    265
      backend/db/survey-generator.js
  41. 0
    341930
      backend/db/zipcodes.js
  42. 0
    73
      backend/lib/auth/strategies/jwt.js
  43. 0
    32
      backend/lib/index.js
  44. 0
    18
      backend/lib/models/aspect.js
  45. 0
    15
      backend/lib/models/aspect_label.js
  46. 0
    12
      backend/lib/models/authentication.js
  47. 0
    28
      backend/lib/models/grouping.js
  48. 0
    28
      backend/lib/models/matchqueue.js
  49. 0
    11
      backend/lib/models/membership.js
  50. 0
    13
      backend/lib/models/message.js
  51. 0
    45
      backend/lib/models/profile.js
  52. 0
    12
      backend/lib/models/response-key.js
  53. 0
    11
      backend/lib/models/response.js
  54. 0
    25
      backend/lib/models/tag-association.js
  55. 0
    11
      backend/lib/models/tag.js
  56. 5
    9
      backend/lib/models/user.js
  57. 0
    18
      backend/lib/models/zip-code.js
  58. 0
    13
      backend/lib/plugins/filter.js
  59. 0
    9
      backend/lib/plugins/health.js
  60. 0
    35
      backend/lib/plugins/membership.js
  61. 0
    119
      backend/lib/plugins/notification.js
  62. 0
    63
      backend/lib/plugins/profile.js
  63. 0
    28
      backend/lib/plugins/survey.js
  64. 3
    35
      backend/lib/plugins/user.js
  65. 0
    89
      backend/lib/routes/filter/get.js
  66. 0
    69
      backend/lib/routes/health/get.js
  67. 0
    176
      backend/lib/routes/membership/active.js
  68. 0
    150
      backend/lib/routes/membership/join.js
  69. 0
    49
      backend/lib/routes/membership/leave.js
  70. 0
    137
      backend/lib/routes/membership/reveal.js
  71. 0
    53
      backend/lib/routes/notification/index.js
  72. 0
    80
      backend/lib/routes/profile/get.js
  73. 0
    85
      backend/lib/routes/profile/insert.js
  74. 0
    81
      backend/lib/routes/profile/match.js
  75. 0
    97
      backend/lib/routes/profile/patch-queue.js
  76. 0
    107
      backend/lib/routes/profile/queue.js
  77. 0
    107
      backend/lib/routes/profile/respond.js
  78. 0
    118
      backend/lib/routes/profile/score.js
  79. 0
    102
      backend/lib/routes/profile/update.js
  80. 0
    70
      backend/lib/routes/survey/questions.js
  81. 0
    71
      backend/lib/routes/survey/responses.js
  82. 0
    86
      backend/lib/routes/tag/get.js
  83. 0
    91
      backend/lib/routes/tag/reveal.js
  84. 0
    119
      backend/lib/routes/user/create-profile.js
  85. 0
    69
      backend/lib/routes/user/get-session.js
  86. 9
    16
      backend/lib/routes/user/get-user.js
  87. 0
    101
      backend/lib/routes/user/login.js
  88. 0
    59
      backend/lib/routes/user/remove-session.js
  89. 0
    82
      backend/lib/routes/user/send-email.js
  90. 0
    105
      backend/lib/routes/user/signup.js
  91. 0
    69
      backend/lib/routes/user/token.js
  92. 0
    77
      backend/lib/routes/user/validate-session.js
  93. 0
    90
      backend/lib/routes/user/verify-session.js
  94. 0
    12
      backend/lib/schemas/api.js
  95. 0
    13
      backend/lib/schemas/authentication.js
  96. 0
    11
      backend/lib/schemas/errors.js
  97. 0
    8
      backend/lib/schemas/filter.js
  98. 0
    28
      backend/lib/schemas/groupings.js
  99. 0
    10
      backend/lib/schemas/health.js
  100. 0
    0
      backend/lib/schemas/memberships.js

+ 0
- 30
backend/db/data-generator/classes.js Dosyayı Görüntüle

@@ -1,30 +0,0 @@
1
-class User {
2
-    constructor(id) {
3
-        this.user_id = id
4
-        this.user_name = ''
5
-        this.user_email = ''
6
-        this.is_admin = false
7
-        this.is_poster = false
8
-        this.is_verified = false
9
-    }
10
-}
11
-class Profile {
12
-    constructor(id, override) {
13
-        this.user_id = override?.user_id ? override.user_id : id
14
-        this.profile_id = override?.profile_id ? override.profile_id + id : id
15
-    }
16
-}
17
-class Response {
18
-    constructor(id) {
19
-        this.response_id = id
20
-        this.profile_id = null
21
-        this.response_key_id = null
22
-        this.val = null
23
-    }
24
-}
25
-
26
-module.exports = {
27
-    User,
28
-    Profile,
29
-    Response,
30
-}

+ 0
- 46
backend/db/data-generator/config.json Dosyayı Görüntüle

@@ -1,46 +0,0 @@
1
-{
2
-    "mockOutputPath": "./db/generated",
3
-    "magic": 1000,
4
-    "total": 100,
5
-    "ignore": [],
6
-    "batchSize": 10,
7
-    "percentageOfSeekers": 90,
8
-    "scoreVals": [1, 2, 3, 4, 5, 6, 7],
9
-    "header": "/**\n* GENERATED MOCK SIIMEE DATA\n*/",
10
-    "possibleZipcodes": [
11
-        "90012",
12
-        "90040",
13
-        "90058",
14
-        "90064",
15
-        "90065",
16
-        "90240",
17
-        "90274",
18
-        "90278",
19
-        "90280",
20
-        "90290",
21
-        "90291",
22
-        "90292",
23
-        "90293",
24
-        "90840",
25
-        "91001",
26
-        "91011",
27
-        "91030",
28
-        "91201",
29
-        "91399",
30
-        "91401",
31
-        "97075"
32
-    ],
33
-    "scoreKeys": [1, 2, 3, 4, 5, 6],
34
-    "nameKey": 7,
35
-    "emailKey": 8,
36
-    "passwordKey": 9,
37
-    "zipcodeKey": 10,
38
-    "mediaKey": 12,
39
-    "langKey": 13,
40
-    "durationKey": 14,
41
-    "presenceKey": 15,
42
-    "blurbKey": 16,
43
-    "urgencyKey": 17,
44
-    "pronounsKey": 18,
45
-    "distanceKey": 19
46
-}

+ 0
- 197
backend/db/data-generator/generate.ipynb Dosyayı Görüntüle

@@ -1,197 +0,0 @@
1
-{
2
- "cells": [
3
-  {
4
-   "cell_type": "code",
5
-   "execution_count": 10,
6
-   "metadata": {},
7
-   "outputs": [
8
-    {
9
-     "name": "stdout",
10
-     "output_type": "stream",
11
-     "text": [
12
-      "\n",
13
-      "Scoring: ((1, 1), (7, 7))\n",
14
-      "1515\n",
15
-      "\n",
16
-      "Scoring: ((2, 1), (2, 2))\n",
17
-      "9000\n",
18
-      "\n",
19
-      "Scoring: ((2, 7), (6, 3))\n",
20
-      "4343\n",
21
-      "\n",
22
-      "Scoring: ((6, 3), (1, 2))\n",
23
-      "4901\n",
24
-      "\n",
25
-      "Scoring: ((5, 6), (4, 6))\n",
26
-      "9000\n",
27
-      "\n",
28
-      "Scoring: ((1, 2), (3, 3))\n",
29
-      "7764\n",
30
-      "\n",
31
-      "Scoring: ((1, 1), (1, 1))\n",
32
-      "10000\n"
33
-     ]
34
-    }
35
-   ],
36
-   "source": [
37
-    "import json\n",
38
-    "import copy\n",
39
-    "from itertools import product\n",
40
-    "from scipy import spatial\n",
41
-    "import math\n",
42
-    "import numpy\n",
43
-    "\n",
44
-    " \n",
45
-    "f = open('./config.json')\n",
46
-    "from_json_config = json.load(f)\n",
47
-    "config = {}\n",
48
-    "config[\"all_possible_responses\"] = from_json_config[\"scoreVals\"]\n",
49
-    "config[\"magic\"] = from_json_config[\"magic\"]\n",
50
-    "config[\"aspect_size\"] = 2\n",
51
-    "config[\"write\"]= True\n",
52
-    "config[\"file\"] = \"../generated/prescore_matrix.json\"\n",
53
-    "config[\"delimiter\"] = \"-\"\n",
54
-    "config[\"version\"] = \"0.1.0\"\n",
55
-    "# max distance = distance between top left and bottom right indices in matrix\n",
56
-    "config[\"max_euclidean_distance\"] =  math.sqrt(\n",
57
-    "    math.pow(len(config[\"all_possible_responses\"])-1, 2) +\n",
58
-    "    math.pow(len(config[\"all_possible_responses\"])-1, 2)\n",
59
-    "    ) \n",
60
-    "f.close()\n",
61
-    "\n",
62
-    "def createPermutations(possibilities, size):\n",
63
-    "    return tuple(product(possibilities, repeat=size))\n",
64
-    "\n",
65
-    "\n",
66
-    "def getAspectFromSurveys(survey_a, survey_b, size):\n",
67
-    "    if (survey_a.__len__() < size | survey_b.__len__() < size):\n",
68
-    "        raise Exception(\"Surveys must both contain more items than size\")\n",
69
-    "\n",
70
-    "    def store(survey, length):\n",
71
-    "        col = []\n",
72
-    "        for i in range(size):\n",
73
-    "            val = survey.pop(0)\n",
74
-    "            col.append(val)\n",
75
-    "        return col\n",
76
-    "\n",
77
-    "    # Take the first <size> elements from the list\n",
78
-    "    col_a = tuple(store(survey_a, size))\n",
79
-    "    col_b = tuple(store(survey_b, size))\n",
80
-    "\n",
81
-    "    if (col_a.__len__() != size | col_b.__len__() != size ):\n",
82
-    "        raise Exception(\"No aspect values found in survey\")\n",
83
-    "\n",
84
-    "    return (col_a, col_b)\n",
85
-    "\n",
86
-    "\n",
87
-    "def scoreAspect(aspect_ab):\n",
88
-    "    a = aspect_ab[0]\n",
89
-    "    b = aspect_ab[1]\n",
90
-    "    return (1 - spatial.distance.cosine(a,b)) * config[\"magic\"]\n",
91
-    "\n",
92
-    "def euclideanDistance(aspect_ab):\n",
93
-    "    a = numpy.array(aspect_ab[0])\n",
94
-    "    b = numpy.array(aspect_ab[1])\n",
95
-    "    return numpy.linalg.norm(a - b)\n",
96
-    "\n",
97
-    "def prescore_matrix_from(vals):\n",
98
-    "    m = {}\n",
99
-    "    for val in vals:\n",
100
-    "        m[val] = []\n",
101
-    "        for other_val in vals:\n",
102
-    "            distance = euclideanDistance((val,other_val))\n",
103
-    "            score = (config[\"max_euclidean_distance\"] - distance) * config[\"magic\"] + 1515\n",
104
-    "            # score = scoreAspect((val, other_val))\n",
105
-    "            adjusted_score = round(score)\n",
106
-    "            m[val].append(adjusted_score)\n",
107
-    "    return m\n",
108
-    "\n",
109
-    "\n",
110
-    "def lookup_prescore_in(score_matrix, vals, aspect_ab):\n",
111
-    "    print(\"\\nScoring:\", aspect_ab)\n",
112
-    "    aspect_a, aspect_b = aspect_ab\n",
113
-    "    # Look-up using the index because\n",
114
-    "    # \n",
115
-    "    pos_b = vals.index(aspect_b)\n",
116
-    "    return score_matrix[aspect_a][pos_b]\n",
117
-    "\n",
118
-    "\n",
119
-    "# !: Mutates your input\n",
120
-    "def score_aspect(input_a, input_b, score_matrix, vals):\n",
121
-    "    aspect_ab = getAspectFromSurveys(input_a, input_b, config[\"aspect_size\"])\n",
122
-    "    return lookup_prescore_in(score_matrix, vals, aspect_ab)\n",
123
-    "\n",
124
-    "\n",
125
-    "def run():\n",
126
-    "    # Set the keys for the look-up\n",
127
-    "    xy_axis_vals = createPermutations(config[\"all_possible_responses\"], config[\"aspect_size\"])\n",
128
-    "    m = prescore_matrix_from(xy_axis_vals)\n",
129
-    "\n",
130
-    "    # Example:\n",
131
-    "    res = config[\"all_possible_responses\"]\n",
132
-    "    input_a = [\n",
133
-    "        res[0], res[0], # One aspect\n",
134
-    "        res[1], res[0],\n",
135
-    "        res[1], res[6],\n",
136
-    "        res[5], res[2],\n",
137
-    "        res[4], res[5],\n",
138
-    "        res[0], res[1],\n",
139
-    "        res[0], res[0],\n",
140
-    "    ]\n",
141
-    "    input_b = [\n",
142
-    "        res[6], res[6], # One aspect\n",
143
-    "        res[1], res[1],\n",
144
-    "        res[5], res[2],\n",
145
-    "        res[0], res[1],\n",
146
-    "        res[3], res[5],\n",
147
-    "        res[2], res[2],\n",
148
-    "        res[0], res[0],\n",
149
-    "    ]\n",
150
-    "    for i in range(round(input_a.__len__() / 2)):\n",
151
-    "        print(score_aspect(input_a, input_b, m, xy_axis_vals))\n",
152
-    "\n",
153
-    "\n",
154
-    "    if(config[\"write\"] == True):\n",
155
-    "        # Serializing json\n",
156
-    "        str_m = {}\n",
157
-    "        for key, values in m.items():\n",
158
-    "            delimiter = config[\"delimiter\"]\n",
159
-    "            str_key = delimiter.join([str(v) for v in key])\n",
160
-    "            str_m[str_key] = [int(val) for val in values]\n",
161
-    "            str_m[\"_config\"] = config\n",
162
-    "        json_object = json.dumps(str_m, indent = 4)\n",
163
-    "        with open(config[\"file\"], \"w\") as file:\n",
164
-    "            # write to file\n",
165
-    "            file.write(json_object)\n",
166
-    "run()\n"
167
-   ]
168
-  }
169
- ],
170
- "metadata": {
171
-  "kernelspec": {
172
-   "display_name": "Python 3.10.6 64-bit",
173
-   "language": "python",
174
-   "name": "python3"
175
-  },
176
-  "language_info": {
177
-   "codemirror_mode": {
178
-    "name": "ipython",
179
-    "version": 3
180
-   },
181
-   "file_extension": ".py",
182
-   "mimetype": "text/x-python",
183
-   "name": "python",
184
-   "nbconvert_exporter": "python",
185
-   "pygments_lexer": "ipython3",
186
-   "version": "3.10.6"
187
-  },
188
-  "orig_nbformat": 4,
189
-  "vscode": {
190
-   "interpreter": {
191
-    "hash": "b0fa6594d8f4cbf19f97940f81e996739fb7646882a419484c72d19e05852a7e"
192
-   }
193
-  }
194
- },
195
- "nbformat": 4,
196
- "nbformat_minor": 2
197
-}

+ 0
- 187
backend/db/data-generator/index.js Dosyayı Görüntüle

@@ -1,187 +0,0 @@
1
-const fs = require('fs')
2
-const config = require('./config')
3
-const random = require('./random')
4
-const classes = require('./classes')
5
-const mock = require('./mock')
6
-
7
-let batchCount = 1 // Counter to track how many things we've generated
8
-let extraProfilesToGenerate = 1
9
-let extraProfileCount = 0 // Counter to track how many EXTRA profiles we've generated
10
-let generatedResponseCount = 0 // Counter to track every response generated
11
-
12
-// Values for responsess as strings
13
-const possibleResponses = {
14
-    not_important: null,
15
-    some_what_important: null,
16
-    important: null,
17
-    very_important: null,
18
-    extremely_important: null,
19
-    mandatory: null,
20
-}
21
-for (let i = 0; i < Object.keys(possibleResponses).length; i++) {
22
-    const key = Object.keys(possibleResponses)[i]
23
-    possibleResponses[key] = config.scoreVals[i].toString()
24
-}
25
-
26
-/**
27
- * Our initial file setup
28
- */
29
-const write = async (batchNum, outputDataObject) => {
30
-    const filename = `_batch_${batchNum}.js`
31
-    await fs.writeFile(`${config.mockOutputPath}/${filename}`, '', () => {})
32
-    fs.appendFile(
33
-        `${config.mockOutputPath}/${filename}`,
34
-        config.header +
35
-            'module.exports = ' +
36
-            JSON.stringify(outputDataObject, null, '  '),
37
-        err => {
38
-            if (err) {
39
-                console.error(err)
40
-                return
41
-            }
42
-        },
43
-    )
44
-}
45
-
46
-// Helper functions
47
-const generate = (classObj, amount, meta) => {
48
-    const instances = []
49
-    for (let i = 0; i < amount; i++) {
50
-        let startFrom = meta?.starting ? meta.starting - config.batchSize : 0
51
-        instances.push(new classObj(i + startFrom + 1, meta))
52
-    }
53
-    return instances
54
-}
55
-
56
-console.log('\nStarting...\n---')
57
-
58
-/**
59
- * Generate Users
60
- */
61
-const generateUsers = () => {
62
-    let users = generate(classes.User, config.batchSize, {
63
-        starting: config.batchSize * batchCount,
64
-    })
65
-    users.forEach(user => {
66
-        user.is_poster = random.number(100) > config.percentageOfSeekers ? 1 : 0
67
-        if (user.is_poster) {
68
-            extraProfilesToGenerate = extraProfilesToGenerate + random.number(2)
69
-        }
70
-        user.user_name = random.name() + ' ' + random.name()
71
-        user.user_email = random.email()
72
-    })
73
-    console.log('COMPLETED: Generated Users...')
74
-    return users
75
-}
76
-
77
-/**
78
- * Generate Profiles
79
- */
80
-const generateProfiles = jobPosterIds => {
81
-    let profiles = generate(classes.Profile, config.batchSize, {
82
-        starting: config.batchSize * batchCount,
83
-        profile_id: extraProfileCount,
84
-    })
85
-
86
-    // Generate extra job posting profiles
87
-    // attributed to random user.is_poster === true
88
-    // TODO: Clean this up. Hard to read...
89
-    if (extraProfilesToGenerate > 0) {
90
-        let extras = []
91
-        for (let l = 0; l < extraProfilesToGenerate; l++) {
92
-            const generatedExtraProfiles = generate(classes.Profile, 1, {
93
-                user_id:
94
-                    jobPosterIds.length > 1
95
-                        ? random.valFrom(jobPosterIds)
96
-                        : jobPosterIds[0],
97
-                profile_id:
98
-                    config.batchSize * batchCount + extraProfileCount + l,
99
-            })
100
-            extras = [...extras, ...generatedExtraProfiles]
101
-        }
102
-        extras.forEach(profile => {
103
-            profiles.push(profile)
104
-            extraProfileCount++
105
-        })
106
-    }
107
-    console.log('COMPLETED: Generated Profiles...')
108
-    return profiles
109
-}
110
-
111
-/**
112
- * Generate Responses
113
- */
114
-const generateResponses = profiles => {
115
-    // Generate responses first, before filling in details
116
-    let responses = generate(
117
-        classes.Response,
118
-        (config.batchSize + extraProfilesToGenerate) *
119
-            mock.response_keys.length,
120
-        { starting: generatedResponseCount + config.batchSize },
121
-    )
122
-    profiles.forEach((profile, i) => {
123
-        const startingIndex = i * mock.response_keys.length
124
-        for (let k = 0; k < mock.response_keys.length; k++) {
125
-            const resToEdit = responses[startingIndex + k]
126
-            resToEdit.response_key_id = k + 1
127
-            resToEdit.profile_id = profile.profile_id
128
-
129
-            if (resToEdit.response_key_id < config.zipcodeKey) {
130
-                resToEdit.val = random.valFrom(Object.values(possibleResponses))
131
-            } else if (resToEdit.response_key_id == config.zipcodeKey) {
132
-                resToEdit.val = random.valFrom(config.possibleZipcodes)
133
-            } else {
134
-                switch (resToEdit.response_key_id) {
135
-                    case config.mediaKey:
136
-                        resToEdit.val = random.media()
137
-                        break
138
-                    case config.langKey:
139
-                        resToEdit.val = random.language()
140
-                        break
141
-                    case config.durationKey:
142
-                        resToEdit.val = random.duration()
143
-                        break
144
-                    case config.presenceKey:
145
-                        resToEdit.val = random.location()
146
-                        break
147
-                    case config.blurbKey:
148
-                        resToEdit.val = random.blurb()
149
-                        break
150
-                }
151
-            }
152
-        }
153
-    })
154
-    generatedResponseCount = generatedResponseCount + responses.length
155
-    console.log('COMPLETED: Generated Responses...')
156
-    return responses
157
-}
158
-
159
-/**
160
- * Our main generator loop
161
- */
162
-for (
163
-    let batch = config.batchSize;
164
-    batch <= config.total;
165
-    batch += config.batchSize
166
-) {
167
-    const users = generateUsers()
168
-
169
-    let jobPosterIds = users
170
-        .filter(user => user.is_poster > 0)
171
-        .map(user => user.user_id)
172
-    // Guarantee ONE job poster
173
-    if (!jobPosterIds.length) {
174
-        random.valFrom(users).is_poster = 1
175
-        jobPosterIds = users
176
-            .filter(user => user.is_poster > 0)
177
-            .map(user => user.user_id)
178
-    }
179
-
180
-    const profiles = generateProfiles(jobPosterIds)
181
-    const responses = generateResponses(profiles)
182
-
183
-    write(config.batchSize * batchCount, { users, profiles, responses })
184
-    batchCount++
185
-}
186
-
187
-console.log('---\nFINISHED...\n===\n')

+ 0
- 230
backend/db/data-generator/lorem.js Dosyayı Görüntüle

@@ -1,230 +0,0 @@
1
-/**
2
- * @fileOverview Generates "Lorem ipsum" style text.
3
- * @author rviscomi@gmail.com Rick Viscomi,
4
- * 		tinsley@tinsology.net Mathew Tinsley
5
- * @version 1.0
6
- */
7
-
8
-/**
9
- *	Copyright (c) 2009, Mathew Tinsley (tinsley@tinsology.net)
10
- *	All rights reserved.
11
- *
12
- *	Redistribution and use in source and binary forms, with or without
13
- *	modification, are permitted provided that the following conditions are met:
14
- *		* Redistributions of source code must retain the above copyright
15
- *		  notice, this list of conditions and the following disclaimer.
16
- *		* Redistributions in binary form must reproduce the above copyright
17
- *		  notice, this list of conditions and the following disclaimer in the
18
- *		  documentation and/or other materials provided with the distribution.
19
- *		* Neither the name of the organization nor the
20
- *		  names of its contributors may be used to endorse or promote products
21
- *		  derived from this software without specific prior written permission.
22
- *
23
- *	THIS SOFTWARE IS PROVIDED BY MATHEW TINSLEY ''AS IS'' AND ANY
24
- *	EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25
- *	WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26
- *	DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
27
- *	DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28
- *	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29
- *	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30
- *	ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31
- *	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32
- *	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
- */
34
-
35
-/**
36
- * @class Jibborish generator.
37
- */
38
-var LoremIpsum = function () {};
39
-
40
-/**
41
- * Average number of words per sentence.
42
- * @constant {number}
43
- */
44
-LoremIpsum.WORDS_PER_SENTENCE_AVG = 24.460;
45
-
46
-/**
47
- * Standard deviation of the number of words per sentence.
48
- * @constant {number}
49
- */
50
-LoremIpsum.WORDS_PER_SENTENCE_STD = 5.080;
51
-
52
-/**
53
- * List of possible words.
54
- * @constant {Array.string}
55
- */
56
-LoremIpsum.WORDS = [
57
-		'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur',
58
-		'adipiscing', 'elit', 'curabitur', 'vel', 'hendrerit', 'libero',
59
-		'eleifend', 'blandit', 'nunc', 'ornare', 'odio', 'ut',
60
-		'orci', 'gravida', 'imperdiet', 'nullam', 'purus', 'lacinia',
61
-		'a', 'pretium', 'quis', 'congue', 'praesent', 'sagittis', 
62
-		'laoreet', 'auctor', 'mauris', 'non', 'velit', 'eros',
63
-		'dictum', 'proin', 'accumsan', 'sapien', 'nec', 'massa',
64
-		'volutpat', 'venenatis', 'sed', 'eu', 'molestie', 'lacus',
65
-		'quisque', 'porttitor', 'ligula', 'dui', 'mollis', 'tempus',
66
-		'at', 'magna', 'vestibulum', 'turpis', 'ac', 'diam',
67
-		'tincidunt', 'id', 'condimentum', 'enim', 'sodales', 'in',
68
-		'hac', 'habitasse', 'platea', 'dictumst', 'aenean', 'neque',
69
-		'fusce', 'augue', 'leo', 'eget', 'semper', 'mattis', 
70
-		'tortor', 'scelerisque', 'nulla', 'interdum', 'tellus', 'malesuada',
71
-		'rhoncus', 'porta', 'sem', 'aliquet', 'et', 'nam',
72
-		'suspendisse', 'potenti', 'vivamus', 'luctus', 'fringilla', 'erat',
73
-		'donec', 'justo', 'vehicula', 'ultricies', 'varius', 'ante',
74
-		'primis', 'faucibus', 'ultrices', 'posuere', 'cubilia', 'curae',
75
-		'etiam', 'cursus', 'aliquam', 'quam', 'dapibus', 'nisl',
76
-		'feugiat', 'egestas', 'class', 'aptent', 'taciti', 'sociosqu',
77
-		'ad', 'litora', 'torquent', 'per', 'conubia', 'nostra',
78
-		'inceptos', 'himenaeos', 'phasellus', 'nibh', 'pulvinar', 'vitae',
79
-		'urna', 'iaculis', 'lobortis', 'nisi', 'viverra', 'arcu',
80
-		'morbi', 'pellentesque', 'metus', 'commodo', 'ut', 'facilisis',
81
-		'felis', 'tristique', 'ullamcorper', 'placerat', 'aenean', 'convallis',
82
-		'sollicitudin', 'integer', 'rutrum', 'duis', 'est', 'etiam',
83
-		'bibendum', 'donec', 'pharetra', 'vulputate', 'maecenas', 'mi',
84
-		'fermentum', 'consequat', 'suscipit', 'aliquam', 'habitant', 'senectus',
85
-		'netus', 'fames', 'quisque', 'euismod', 'curabitur', 'lectus',
86
-		'elementum', 'tempor', 'risus', 'cras'
87
-];
88
-
89
-/**
90
- * Generate "Lorem ipsum" style words.
91
- * @param num_words {number} Number of words to generate.
92
- * @return {string} "Lorem ipsum..."
93
- */
94
-LoremIpsum.prototype.generate = function (num_words) {
95
-	var words, ii, position, word, current, sentences, sentence_length, sentence;
96
-	
97
-	/**
98
-	 * @default 100
99
-	 */
100
-	num_words = num_words || 100;
101
-	
102
-	words = [LoremIpsum.WORDS[0], LoremIpsum.WORDS[1]];
103
-	num_words -= 2;
104
-	
105
-	for (ii = 0; ii < num_words; ii++) {
106
-		position = Math.floor(Math.random() * LoremIpsum.WORDS.length);
107
-		word = LoremIpsum.WORDS[position];
108
-		
109
-		if (ii > 0 && words[ii - 1] === word) {
110
-			ii -= 1;
111
-			
112
-		} else {
113
-			words[ii] = word;
114
-		}
115
-	}
116
-	
117
-	sentences = [];
118
-	current = 0;
119
-	
120
-	while (num_words > 0) {
121
-		sentence_length = this.getRandomSentenceLength();
122
-		
123
-		if (num_words - sentence_length < 4) {
124
-			sentence_length = num_words;
125
-		}
126
-		
127
-		num_words -= sentence_length;
128
-		
129
-		sentence = [];
130
-		
131
-		for (ii = current; ii < (current + sentence_length); ii++) {
132
-			sentence.push(words[ii]);
133
-		}
134
-		
135
-		sentence = this.punctuate(sentence);
136
-		current += sentence_length;
137
-		sentences.push(sentence.join(' '));
138
-	}
139
-	
140
-	return sentences.join(' ');
141
-};
142
-
143
-/**
144
- * Insert commas and periods in the given sentence.
145
- * @param {Array.string} sentence List of words in the sentence.
146
- * @return {Array.string} Sentence with punctuation added.
147
- */
148
-LoremIpsum.prototype.punctuate = function (sentence) {
149
-	var word_length, num_commas, ii, position;
150
-	
151
-	word_length = sentence.length;
152
-	
153
-	/* End the sentence with a period. */
154
-	sentence[word_length - 1] += '.';
155
-	
156
-	if (word_length < 4) {
157
-		return sentence;
158
-	}
159
-	
160
-	num_commas = this.getRandomCommaCount(word_length);
161
-	
162
-	for (ii = 0; ii <= num_commas; ii++) {
163
-		position = Math.round(ii * word_length / (num_commas + 1));
164
-		
165
-		if (position < (word_length - 1) && position > 0) {
166
-			/* Add the comma. */
167
-			sentence[position] += ',';
168
-		}
169
-	}
170
-	
171
-	/* Capitalize the first word in the sentence. */
172
-	sentence[0] = sentence[0].charAt(0).toUpperCase() + sentence[0].slice(1);
173
-	
174
-	return sentence;
175
-};
176
-
177
-/**
178
- * Produces a random number of commas.
179
- * @param {number} word_length Number of words in the sentence.
180
- * @return {number} Random number of commas
181
- */
182
-LoremIpsum.prototype.getRandomCommaCount = function (word_length) {
183
-	var base, average, standard_deviation;
184
-	
185
-	/* Arbitrary. */
186
-	base = 6;
187
-	
188
-	average = Math.log(word_length) / Math.log(base);
189
-	standard_deviation = average / base;
190
-	
191
-	return Math.round(this.gaussMS(average, standard_deviation));
192
-};
193
-
194
-/**
195
- * Produces a random sentence length based on the average word length
196
- * of an English sentence.
197
- * @return {number} Random sentence length
198
- */
199
-LoremIpsum.prototype.getRandomSentenceLength = function () {
200
-	return Math.round(
201
-			this.gaussMS(
202
-					LoremIpsum.WORDS_PER_SENTENCE_AVG,
203
-					LoremIpsum.WORDS_PER_SENTENCE_STD
204
-			)
205
-	);
206
-};
207
-
208
-/**
209
- * Produces a random number.
210
- * @return {number} Random number
211
- */
212
-LoremIpsum.prototype.gauss = function () {
213
-	return (Math.random() * 2 - 1) +
214
-			(Math.random() * 2 - 1) +
215
-			(Math.random() * 2 - 1);
216
-};
217
-
218
-/**
219
- * Produces a random number with Gaussian distribution.
220
- * @param {number} mean
221
- * @param {number} standard_deviation
222
- * @return {number} Random number
223
- */
224
-LoremIpsum.prototype.gaussMS = function (mean, standard_deviation) {
225
-	return Math.round(this.gauss() * standard_deviation + mean);
226
-};
227
-
228
-module.exports = {
229
-	LoremIpsum
230
-}

+ 0
- 760
backend/db/data-generator/mock.js Dosyayı Görüntüle

@@ -1,760 +0,0 @@
1
-module.exports = {
2
-    users: [],
3
-    profiles: [],
4
-    tags: [
5
-        {
6
-            tag_id: 1,
7
-            tag_category: 'verification',
8
-            tag_description: 'verified',
9
-            is_active: true,
10
-        },
11
-        {
12
-            tag_id: 2,
13
-            tag_category: 'reveal',
14
-            tag_description: 'verified',
15
-            is_active: true,
16
-        },
17
-        {
18
-            tag_id: 3,
19
-            tag_category: 'reveal',
20
-            tag_description: 'pronoun',
21
-            is_active: true,
22
-        },
23
-        {
24
-            tag_id: 4,
25
-            tag_category: 'reveal',
26
-            tag_description: 'image',
27
-            is_active: true,
28
-        },
29
-        {
30
-            tag_id: 5,
31
-            tag_category: 'reveal',
32
-            tag_description: 'blurb',
33
-            is_active: true,
34
-        },
35
-        {
36
-            tag_id: 6,
37
-            tag_category: 'reveal',
38
-            tag_description: 'urgency',
39
-            is_active: true,
40
-        },
41
-        {
42
-            tag_id: 7,
43
-            tag_category: 'reveal',
44
-            tag_description: 'user_name',
45
-            is_active: true,
46
-        },
47
-        {
48
-            tag_id: 8,
49
-            tag_category: 'reveal',
50
-            tag_description: 'user_email',
51
-            is_active: true,
52
-        },
53
-        {
54
-            tag_id: 9,
55
-            tag_category: 'healthcare--certification',
56
-            tag_description: 'ADM-BC',
57
-            is_active: true,
58
-        },
59
-        {
60
-            tag_id: 10,
61
-            tag_category: 'healthcare--certification',
62
-            tag_description: 'CBHC',
63
-            is_active: true,
64
-        },
65
-        {
66
-            tag_id: 11,
67
-            tag_category: 'healthcare--certification',
68
-            tag_description: 'CEN',
69
-            is_active: true,
70
-        },
71
-        {
72
-            tag_id: 12,
73
-            tag_category: 'healthcare--certification',
74
-            tag_description: 'CFRN',
75
-            is_active: true,
76
-        },
77
-        {
78
-            tag_id: 13,
79
-            tag_category: 'healthcare--certification',
80
-            tag_description: 'CMCN',
81
-            is_active: true,
82
-        },
83
-    ],
84
-    tag_associations: [
85
-        {
86
-            tag_association_id: 1,
87
-            profile_id: 1,
88
-            grouping_id: null,
89
-            tag_id: 1,
90
-            is_deleted: false,
91
-        },
92
-        {
93
-            tag_association_id: 2,
94
-            profile_id: 2,
95
-            grouping_id: null,
96
-            tag_id: 1,
97
-            is_deleted: false,
98
-        },
99
-        {
100
-            tag_association_id: 3,
101
-            profile_id: 3,
102
-            grouping_id: null,
103
-            tag_id: 1,
104
-            is_deleted: false,
105
-        },
106
-        {
107
-            tag_association_id: 4,
108
-            profile_id: 45,
109
-            grouping_id: null,
110
-            tag_id: 1,
111
-            is_deleted: false,
112
-        },
113
-        {
114
-            tag_association_id: 5,
115
-            profile_id: 45,
116
-            grouping_id: 2,
117
-            tag_id: 8,
118
-            is_deleted: false,
119
-        },
120
-        {
121
-            tag_association_id: 6,
122
-            profile_id: 45,
123
-            grouping_id: 2,
124
-            tag_id: 5,
125
-            is_deleted: false,
126
-        },
127
-        {
128
-            tag_association_id: 7,
129
-            profile_id: 2,
130
-            grouping_id: 2,
131
-            tag_id: 5,
132
-            is_deleted: false,
133
-        },
134
-        {
135
-            tag_association_id: 8,
136
-            profile_id: 41,
137
-            grouping_id: 1,
138
-            tag_id: 4,
139
-            is_deleted: false,
140
-        },
141
-        {
142
-            tag_association_id: 9,
143
-            profile_id: 41,
144
-            grouping_id: 1,
145
-            tag_id: 5,
146
-            is_deleted: false,
147
-        },
148
-        {
149
-            tag_association_id: 10,
150
-            profile_id: 4,
151
-            grouping_id: null,
152
-            tag_id: 1,
153
-            is_deleted: false,
154
-        },
155
-        {
156
-            tag_association_id: 11,
157
-            profile_id: 5,
158
-            grouping_id: null,
159
-            tag_id: 1,
160
-            is_deleted: false,
161
-        },
162
-        {
163
-            tag_association_id: 12,
164
-            profile_id: 6,
165
-            grouping_id: null,
166
-            tag_id: 3,
167
-            is_deleted: false,
168
-        },
169
-        {
170
-            tag_association_id: 13,
171
-            profile_id: 7,
172
-            grouping_id: null,
173
-            tag_id: 8,
174
-            is_deleted: false,
175
-        },
176
-        {
177
-            tag_association_id: 14,
178
-            profile_id: 8,
179
-            grouping_id: null,
180
-            tag_id: 7,
181
-            is_deleted: false,
182
-        },
183
-        {
184
-            tag_association_id: 15,
185
-            profile_id: 9,
186
-            grouping_id: 1,
187
-            tag_id: 2,
188
-            is_deleted: false,
189
-        },
190
-        {
191
-            tag_association_id: 16,
192
-            profile_id: 10,
193
-            grouping_id: 2,
194
-            tag_id: 2,
195
-            is_deleted: false,
196
-        },
197
-        {
198
-            tag_association_id: 17,
199
-            profile_id: 11,
200
-            grouping_id: 2,
201
-            tag_id: 3,
202
-            is_deleted: false,
203
-        },
204
-        {
205
-            tag_association_id: 18,
206
-            profile_id: 12,
207
-            grouping_id: 3,
208
-            tag_id: 4,
209
-            is_deleted: false,
210
-        },
211
-        {
212
-            tag_association_id: 19,
213
-            profile_id: 13,
214
-            grouping_id: 3,
215
-            tag_id: 7,
216
-            is_deleted: false,
217
-        },
218
-        {
219
-            tag_association_id: 20,
220
-            profile_id: 14,
221
-            grouping_id: 4,
222
-            tag_id: 6,
223
-            is_deleted: false,
224
-        },
225
-        {
226
-            tag_association_id: 21,
227
-            profile_id: 15,
228
-            grouping_id: 1,
229
-            tag_id: 1,
230
-            is_deleted: false,
231
-        },
232
-        {
233
-            tag_association_id: 22,
234
-            profile_id: 16,
235
-            grouping_id: 1,
236
-            tag_id: 2,
237
-            is_deleted: false,
238
-        },
239
-        {
240
-            tag_association_id: 23,
241
-            profile_id: 17,
242
-            grouping_id: null,
243
-            tag_id: 6,
244
-            is_deleted: false,
245
-        },
246
-        {
247
-            tag_association_id: 24,
248
-            profile_id: 18,
249
-            grouping_id: null,
250
-            tag_id: 8,
251
-            is_deleted: false,
252
-        },
253
-        {
254
-            tag_association_id: 25,
255
-            profile_id: 19,
256
-            grouping_id: null,
257
-            tag_id: 3,
258
-            is_deleted: false,
259
-        },
260
-        {
261
-            tag_association_id: 26,
262
-            profile_id: 20,
263
-            grouping_id: null,
264
-            tag_id: 3,
265
-            is_deleted: false,
266
-        },
267
-        {
268
-            tag_association_id: 27,
269
-            profile_id: 21,
270
-            grouping_id: 2,
271
-            tag_id: 1,
272
-            is_deleted: false,
273
-        },
274
-        {
275
-            tag_association_id: 28,
276
-            profile_id: 22,
277
-            grouping_id: 2,
278
-            tag_id: 1,
279
-            is_deleted: false,
280
-        },
281
-        {
282
-            tag_association_id: 29,
283
-            profile_id: 23,
284
-            grouping_id: 3,
285
-            tag_id: 2,
286
-            is_deleted: false,
287
-        },
288
-        {
289
-            tag_association_id: 30,
290
-            profile_id: 24,
291
-            grouping_id: 4,
292
-            tag_id: 4,
293
-            is_deleted: false,
294
-        },
295
-        {
296
-            tag_association_id: 31,
297
-            profile_id: 25,
298
-            grouping_id: 5,
299
-            tag_id: 3,
300
-            is_deleted: false,
301
-        },
302
-        {
303
-            tag_association_id: 32,
304
-            profile_id: 26,
305
-            grouping_id: 1,
306
-            tag_id: 4,
307
-            is_deleted: false,
308
-        },
309
-        {
310
-            tag_association_id: 33,
311
-            profile_id: 27,
312
-            grouping_id: null,
313
-            tag_id: 3,
314
-            is_deleted: false,
315
-        },
316
-        {
317
-            tag_association_id: 34,
318
-            profile_id: 28,
319
-            grouping_id: null,
320
-            tag_id: 3,
321
-            is_deleted: false,
322
-        },
323
-        {
324
-            tag_association_id: 35,
325
-            profile_id: 29,
326
-            grouping_id: null,
327
-            tag_id: 7,
328
-            is_deleted: false,
329
-        },
330
-        {
331
-            tag_association_id: 36,
332
-            profile_id: 30,
333
-            grouping_id: null,
334
-            tag_id: 6,
335
-            is_deleted: false,
336
-        },
337
-        {
338
-            tag_association_id: 37,
339
-            profile_id: 31,
340
-            grouping_id: 3,
341
-            tag_id: 4,
342
-            is_deleted: false,
343
-        },
344
-        {
345
-            tag_association_id: 38,
346
-            profile_id: 32,
347
-            grouping_id: 3,
348
-            tag_id: 5,
349
-            is_deleted: false,
350
-        },
351
-        {
352
-            tag_association_id: 39,
353
-            profile_id: 33,
354
-            grouping_id: 3,
355
-            tag_id: 5,
356
-            is_deleted: false,
357
-        },
358
-        {
359
-            tag_association_id: 40,
360
-            profile_id: 34,
361
-            grouping_id: 4,
362
-            tag_id: 7,
363
-            is_deleted: false,
364
-        },
365
-        {
366
-            tag_association_id: 41,
367
-            profile_id: 35,
368
-            grouping_id: 4,
369
-            tag_id: 8,
370
-            is_deleted: false,
371
-        },
372
-        {
373
-            tag_association_id: 42,
374
-            profile_id: 36,
375
-            grouping_id: 1,
376
-            tag_id: 1,
377
-            is_deleted: false,
378
-        },
379
-        {
380
-            tag_association_id: 43,
381
-            profile_id: 37,
382
-            grouping_id: 1,
383
-            tag_id: 2,
384
-            is_deleted: false,
385
-        },
386
-        {
387
-            tag_association_id: 44,
388
-            profile_id: 38,
389
-            grouping_id: null,
390
-            tag_id: 2,
391
-            is_deleted: false,
392
-        },
393
-        {
394
-            tag_association_id: 45,
395
-            profile_id: 39,
396
-            grouping_id: null,
397
-            tag_id: 6,
398
-            is_deleted: false,
399
-        },
400
-        {
401
-            tag_association_id: 46,
402
-            profile_id: 40,
403
-            grouping_id: null,
404
-            tag_id: 5,
405
-            is_deleted: false,
406
-        },
407
-        {
408
-            tag_association_id: 47,
409
-            profile_id: 41,
410
-            grouping_id: null,
411
-            tag_id: 6,
412
-            is_deleted: false,
413
-        },
414
-        {
415
-            tag_association_id: 48,
416
-            profile_id: 42,
417
-            grouping_id: 1,
418
-            tag_id: 8,
419
-            is_deleted: false,
420
-        },
421
-        {
422
-            tag_association_id: 49,
423
-            profile_id: 43,
424
-            grouping_id: 1,
425
-            tag_id: 7,
426
-            is_deleted: false,
427
-        },
428
-        // NOTE: profile_id 147 is chosen based off of GENERATED data,
429
-        // after running 'npm run generate', replace 147 in mock to next profile_id to be genearted
430
-        // i.e. last profile_id number + 1
431
-        // TODO: remove from mock data once bare bones matching logic can show poorly matched matches...
432
-        {
433
-            tag_association_id: 50,
434
-            profile_id: 139,
435
-            grouping_id: 2,
436
-            tag_id: 7,
437
-            is_deleted: false,
438
-        },
439
-    ],
440
-    response_keys: [
441
-        {
442
-            response_key_id: 1,
443
-            response_key_category: 'visionary_vs_implementer',
444
-            response_key_prompt:
445
-                'Do you prefer to work with those who are driven by their Visionary insights, or those who are driven more by their Implementation?',
446
-            response_key_description: 'first round draft scoring question',
447
-            aspect: 'visionary_vs_implementer',
448
-            category: 'aspect',
449
-            placeholder: null,
450
-            invalidInputPrompt: null,
451
-        },
452
-        {
453
-            response_key_id: 2,
454
-            response_key_category: 'creative_vs_methodical',
455
-            response_key_prompt:
456
-                'Have you found more success working with employees that are more Creative or those that are more Methodical?',
457
-            response_key_description: 'first round draft scoring question',
458
-            aspect: 'creative_vs_methodical',
459
-            category: 'aspect',
460
-            placeholder: null,
461
-            invalidInputPrompt: null,
462
-        },
463
-        {
464
-            response_key_id: 3,
465
-            response_key_category: 'dynamic_vs_ordered',
466
-            response_key_prompt:
467
-                'Which do you find to be the ideal working environment, one that is more Collaborative or one that is more Independent?',
468
-            response_key_description: 'first round draft scoring question',
469
-            aspect: 'dynamic_vs_ordered',
470
-            category: 'aspect',
471
-            placeholder: null,
472
-            invalidInputPrompt: null,
473
-        },
474
-        {
475
-            response_key_id: 4,
476
-            response_key_category: 'precise_vs_resourceful',
477
-            response_key_prompt:
478
-                'Is the success of your team more likely if it includes individuals who are more Innovative, or those that are more Conventional when fulfilling their job duties?',
479
-            response_key_description: 'first round draft scoring question',
480
-            aspect: 'precise_vs_resourceful',
481
-            category: 'aspect',
482
-            placeholder: null,
483
-            invalidInputPrompt: null,
484
-        },
485
-        {
486
-            response_key_id: 5,
487
-            response_key_category: 'big_Picture_vs_focused',
488
-            response_key_prompt:
489
-                'When fulfilling the role of the hiring leader, do you find yourself focusing more on the Big Picture or The Task At Hand?',
490
-            response_key_description: 'first round draft scoring question',
491
-            aspect: 'big_Picture_vs_focused',
492
-            category: 'aspect',
493
-            placeholder: null,
494
-            invalidInputPrompt: null,
495
-        },
496
-        {
497
-            response_key_id: 6,
498
-            response_key_category: 'guided_vs_self-managed',
499
-            response_key_prompt:
500
-                'Do you prefer to Guide your employees towards achieving the team goals, or do you prefer your employees to be Self-Managed?',
501
-            response_key_description: 'first round draft scoring question',
502
-            aspect: 'guided_vs_self-managed',
503
-            category: 'aspect',
504
-            placeholder: null,
505
-            invalidInputPrompt: null,
506
-        },
507
-        {
508
-            response_key_id: 7,
509
-            response_key_category: 'profile',
510
-            response_key_prompt:
511
-                'First things first, could you provide us with your name? [break] I am called [break] when others address me.',
512
-            response_key_description: 'required for profile creation',
513
-            aspect: null,
514
-            category: 'input',
515
-            placeholder: 'Joe Doe',
516
-            invalidInputPrompt: 'So sorry, but what is your name?',
517
-        },
518
-        {
519
-            response_key_id: 8,
520
-            response_key_category: 'profile',
521
-            response_key_prompt:
522
-                'In order for others to reach out to you on Siimee, we will need you to provide your email address.[break]When reaching out to me, [break] is my preferred email.',
523
-            response_key_description: 'required for profile creation',
524
-            aspect: null,
525
-            category: 'input',
526
-            placeholder: 'joe@mailme.com',
527
-            invalidInputPrompt:
528
-                'It looks like that email is not valid, try en email that is formatted like so: joe@joe.com',
529
-        },
530
-        {
531
-            response_key_id: 9,
532
-            response_key_category: 'profile',
533
-            response_key_prompt:
534
-                'So far so good! Next we will need you to establish a super secret password. Your password should be at least 14 characters long and have at least 2 special characters.[break]My [break] is a very secure passcode that only I will have access to!',
535
-            response_key_description: 'required for profile creation',
536
-            aspect: null,
537
-            category: 'input',
538
-            placeholder: 'supersecr3tp@ssword',
539
-            invalidInputPrompt:
540
-                'That password does not fit our requirements, please follow the above instructions to generate a secure password.',
541
-        },
542
-        {
543
-            response_key_id: 10,
544
-            response_key_category: 'profile',
545
-            response_key_prompt:
546
-                'Looking good! Doing great. The next piece of info needed is your zip code. That way we can be sure to only show you other people in your area.[break]My zip code, [break] is the general area where I wish to see results in.',
547
-            response_key_description: 'required for distance calculations',
548
-            aspect: null,
549
-            category: 'input',
550
-            placeholder: '90012',
551
-            invalidInputPrompt:
552
-                'Oops! That is not a recognized zipcode, please enter a 5 digit zipcode like: 97869',
553
-        },
554
-        {
555
-            response_key_id: 11,
556
-            response_key_category: 'profile',
557
-            response_key_prompt:
558
-                'What are you seeking? Are you looking to find a position to be employed in, or are you looking to employ a candidate?[break] I am a [break] seeking an employer/employee.',
559
-            response_key_description: 'required for profile generation',
560
-            aspect: null,
561
-            category: 'choice',
562
-            placeholder: null,
563
-            invalidInputPrompt:
564
-                'In order to provide you with the best results, Siimee will need to know whether you are an employer looking to fill a position, or a candidate looking for an employment. Please take a look at our above options and choose one.',
565
-        },
566
-        {
567
-            response_key_id: 12,
568
-            response_key_category: 'profile',
569
-            response_key_prompt:
570
-                'Hey, you are almost done! Please provide an image of yourself so others can recognize you if you ever meet up IRL:',
571
-            response_key_description: 'required for profile pictures',
572
-            aspect: null,
573
-            category: 'input',
574
-            placeholder: null,
575
-            invalidInputPrompt:
576
-                'It appears you have yet to upload an image. Please provide Siimee with an image in case you want to show others what you look like.',
577
-        },
578
-        {
579
-            response_key_id: 13,
580
-            response_key_category: 'profile',
581
-            response_key_prompt:
582
-                'What language is your native language?[break] I consider [break] language as my native language.',
583
-            response_key_description:
584
-                'programming and spoken language preference',
585
-            aspect: null,
586
-            category: 'choice',
587
-            placeholder: null,
588
-            invalidInputPrompt:
589
-                'We try our best to provide results in the language of your choosing. ¿Prefieres ver resultados en español? Ou peut-être parlez-vous français? Or would you prefer to see results in english?',
590
-        },
591
-        {
592
-            response_key_id: 14,
593
-            response_key_category: 'profile',
594
-            response_key_prompt:
595
-                'What kind of duration would you prefer? Are you looking for part-time, full-time, other?[break] Currently, I am looking for a [break] job at this time.',
596
-            response_key_description:
597
-                'duration preference for hours able to dedicate to work',
598
-            aspect: null,
599
-            category: 'choice',
600
-            placeholder: null,
601
-            invalidInputPrompt:
602
-                'Looks like you have yet to  fill out what kind of work you are most interested in. As in, part-time, full-time. Take a look at our above options and choose whatever feels right for you right now. You can always edit them later!',
603
-        },
604
-        {
605
-            response_key_id: 15,
606
-            response_key_category: 'profile',
607
-            response_key_prompt:
608
-                'Would you prefer remote, hybrid, in-person work?[break] Personally I would prefer a [break] job right now. It is just what works best for me.',
609
-            response_key_description:
610
-                'location preference for where work happens',
611
-            aspect: null,
612
-            category: 'choice',
613
-            placeholder: null,
614
-            invalidInputPrompt:
615
-                'Hold up! So sorry to put a pause here, but it looks like you have not chosen whether to work remotely or in person. No worries, if you are unsure, just choose the flexible option.',
616
-        },
617
-        {
618
-            response_key_id: 16,
619
-            response_key_category: 'profile',
620
-            response_key_prompt:
621
-                'Please provide us with a short blurb about yourself. What is your backstory?[break] My origin story starts like this:[break]',
622
-            response_key_description: 'required for profile description',
623
-            aspect: null,
624
-            category: 'input',
625
-            placeholder: 'my backstory starts long long ago...',
626
-            invalidInputPrompt:
627
-                'Whoa! Cool story. Unfortunately your backstory is either too long or too short. Please tell us a bit about yourself between 1 and 100 characters.',
628
-        },
629
-        {
630
-            response_key_id: 17,
631
-            response_key_category: 'profile',
632
-            response_key_prompt:
633
-                'How soon do you need the position filled or you need to be employed? [break]I am currently [break] when it comes to employment opportunities right now.',
634
-            response_key_description: 'urgency for when work is required',
635
-            aspect: null,
636
-            category: 'choice',
637
-            placeholder: null,
638
-            invalidInputPrompt:
639
-                'Looks like you left this field blank. Take a look at our provided options and tell us when you would like be employed.',
640
-        },
641
-        {
642
-            response_key_id: 18,
643
-            response_key_category: 'profile',
644
-            response_key_prompt:
645
-                'When others refer to you, what pronouns do you prefer they use?[break]I prefer to be called [break] when others refer to me.',
646
-            response_key_description: 'required for profile pronouns',
647
-            aspect: null,
648
-            category: 'choice',
649
-            placeholder: null,
650
-            invalidInputPrompt:
651
-                'Ensuring that others on our platform are aware of what your preferred pronouns are is important to us. Please choose from one of the above options.',
652
-        },
653
-        {
654
-            response_key_id: 19,
655
-            response_key_category: 'profile',
656
-            response_key_prompt:
657
-                'What distance from your home are you looking to work in?[break] Preferably, I would like to work [break] from my place of residence.',
658
-            response_key_description:
659
-                'preference for commuting distance cutoff',
660
-            aspect: null,
661
-            category: 'input',
662
-            placeholder: '5 mi',
663
-            invalidInputPrompt:
664
-                'Whoa! You either left this field blank or tried to input an astronomically large distance you would like to see results from. Please input a distance you would like to see results in.',
665
-        },
666
-    ],
667
-    responses: [],
668
-    memberships: [
669
-        {
670
-            membership_id: 1,
671
-            profile_id: 41,
672
-            grouping_id: 1,
673
-            membership_type: 'participant',
674
-            can_edit: false,
675
-            is_active: true,
676
-        },
677
-        {
678
-            membership_id: 2,
679
-            profile_id: 46,
680
-            grouping_id: 1,
681
-            membership_type: 'participant',
682
-            can_edit: false,
683
-            is_active: true,
684
-        },
685
-        {
686
-            membership_id: 4,
687
-            profile_id: 46,
688
-            grouping_id: 2,
689
-            membership_type: 'participant',
690
-            can_edit: false,
691
-            is_active: true,
692
-        },
693
-    ],
694
-    groupings: [
695
-        {
696
-            grouping_id: 1,
697
-            grouping_name: '1663285820.067_41_46',
698
-            grouping_type: 'match',
699
-        },
700
-        {
701
-            grouping_id: 2,
702
-            grouping_name: '1663285820.067_147_46',
703
-            grouping_type: 'match',
704
-        },
705
-    ],
706
-    messages: [],
707
-    match_queues: [
708
-        { match_queue_id: 1, profile_id: 47, target_id: 62, is_deleted: false },
709
-        { match_queue_id: 2, profile_id: 62, target_id: 47, is_deleted: false },
710
-        { match_queue_id: 3, profile_id: 62, target_id: 46, is_deleted: false },
711
-        { match_queue_id: 4, profile_id: 46, target_id: 62, is_deleted: false },
712
-        { match_queue_id: 5, profile_id: 47, target_id: 46, is_deleted: false },
713
-        { match_queue_id: 6, profile_id: 46, target_id: 48, is_deleted: false },
714
-        { match_queue_id: 7, profile_id: 46, target_id: 44, is_deleted: false },
715
-        { match_queue_id: 8, profile_id: 46, target_id: 43, is_deleted: false },
716
-        { match_queue_id: 9, profile_id: 46, target_id: 42, is_deleted: false },
717
-        {
718
-            match_queue_id: 10,
719
-            profile_id: 46,
720
-            target_id: 41,
721
-            is_deleted: false,
722
-        },
723
-        {
724
-            match_queue_id: 11,
725
-            profile_id: 46,
726
-            target_id: 40,
727
-            is_deleted: false,
728
-        },
729
-        {
730
-            match_queue_id: 12,
731
-            profile_id: 40,
732
-            target_id: 46,
733
-            is_deleted: false,
734
-        },
735
-        {
736
-            match_queue_id: 13,
737
-            profile_id: 41,
738
-            target_id: 46,
739
-            is_deleted: false,
740
-        },
741
-        {
742
-            match_queue_id: 14,
743
-            profile_id: 42,
744
-            target_id: 46,
745
-            is_deleted: false,
746
-        },
747
-        {
748
-            match_queue_id: 15,
749
-            profile_id: 43,
750
-            target_id: 46,
751
-            is_deleted: false,
752
-        },
753
-        {
754
-            match_queue_id: 16,
755
-            profile_id: 44,
756
-            target_id: 46,
757
-            is_deleted: false,
758
-        },
759
-    ],
760
-}

+ 0
- 109
backend/db/data-generator/random.js Dosyayı Görüntüle

@@ -1,109 +0,0 @@
1
-const lipsum = require('./lorem')
2
-
3
-const randomNumber = max => {
4
-    return Math.floor(Math.random() * max) < 1
5
-        ? 1
6
-        : Math.floor(Math.random() * max)
7
-}
8
-const randomValFrom = arr => arr[randomNumber(arr.length)]
9
-const randomEmail = (length = 5) => {
10
-    let chars =
11
-        'abcdefghijklmnopqrstuvwxyz-_abcdefghijklmnopqrstuvwxyz0123456789'
12
-    let str = ''
13
-    for (let i = 0; i < length + randomNumber(9); i++) {
14
-        str += chars.charAt(Math.floor(Math.random() * chars.length))
15
-    }
16
-    const suffixs = [
17
-        '@gmail.com',
18
-        '@aol.com',
19
-        '@yahoo.com',
20
-        '@apple.com',
21
-        '@hotmail.com',
22
-        '@rocket-mail.com',
23
-        '@mail.com',
24
-    ]
25
-    return str + randomValFrom(suffixs)
26
-}
27
-const randomName = (length = 4) => {
28
-    let chars = 'aeiouaeiouabcdefghijklmnoprstuvwyabcdefghijklmnopqrstuvwxyz'
29
-    let str = ''
30
-    for (let i = 0; i < length + randomNumber(9); i++) {
31
-        str += chars.charAt(Math.floor(Math.random() * chars.length))
32
-    }
33
-    return str
34
-}
35
-const randomMedia = () => {
36
-    const stockimg = [
37
-        'https://i.imgur.com/a4wirDS.png',
38
-        'https://i.imgur.com/F6GxGXG.jpeg',
39
-        'https://i.imgur.com/ekrkdNt.jpeg',
40
-        'https://i.imgur.com/VtMTfDg.jpeg',
41
-        'https://i.imgur.com/9Fwouqm.jpeg',
42
-        'https://i.imgur.com/rOjRCgo.jpeg',
43
-        'https://i.imgur.com/FwSdQww.jpeg',
44
-        'https://i.imgur.com/JjZyzXL.jpeg',
45
-        'https://i.imgur.com/1DsSQ1s.jpeg',
46
-    ]
47
-    return randomValFrom(stockimg)
48
-}
49
-
50
-const randomLang = () => {
51
-    const langs = [
52
-        'javascript',
53
-        'python',
54
-        'ruby',
55
-        'erlang',
56
-        'haskall',
57
-        'php',
58
-        'swift',
59
-        'rust',
60
-        'objective-c',
61
-        'common lisp',
62
-        'java',
63
-        'perl',
64
-        'cobol',
65
-        'fortran',
66
-        'julia',
67
-        'c#',
68
-        'go',
69
-        'c++',
70
-    ]
71
-    return randomValFrom(langs)
72
-}
73
-
74
-const randomDuration = () => {
75
-    const duration = ['full', 'part']
76
-    return randomValFrom(duration)
77
-}
78
-
79
-const randomLocation = () => {
80
-    const location = ['onsite', 'remote', 'flexible']
81
-    return randomValFrom(location)
82
-}
83
-
84
-const randomBlurb = () => {
85
-    const l = new lipsum.LoremIpsum()
86
-    return l.generate(randomNumber(50))
87
-}
88
-
89
-
90
-module.exports = {
91
-    randomNumber,
92
-    randomValFrom,
93
-    randomEmail,
94
-    randomName,
95
-    randomMedia,
96
-    randomLang,
97
-    randomDuration,
98
-    randomLocation,
99
-    randomBlurb,
100
-    number: randomNumber,
101
-    valFrom: randomValFrom,
102
-    email: randomEmail,
103
-    name: randomName,
104
-    media: randomMedia,
105
-    language: randomLang,
106
-    duration: randomDuration,
107
-    location: randomLocation,
108
-    blurb: randomBlurb
109
-}

+ 0
- 3
backend/db/dataSort.js Dosyayı Görüntüle

@@ -1,3 +0,0 @@
1
-const dataSort = (table, id) => table.sort((a, b) => a[`${id}`] < b[`${id}`])
2
-
3
-module.exports = dataSort

+ 0
- 2519
backend/db/generated/prescore_matrix.json
Dosya farkı çok büyük olduğundan ihmal edildi
Dosyayı Görüntüle


+ 1
- 1
backend/db/knex.js Dosyayı Görüntüle

@@ -1,3 +1,3 @@
1 1
 const environment = process.env.NODE_ENV || 'development'
2 2
 const config = require('../knexfile')[environment]
3
-module.exports = require('knex')(config)
3
+module.exports = require('knex')(config)

backend/db/migrations/20210524105357_create_users_table.js → backend/db/migrations/20210524105357_users.js Dosyayı Görüntüle


+ 0
- 10
backend/db/migrations/20210527173933_create_profiles_table.js Dosyayı Görüntüle

@@ -1,10 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('profiles', function (table) {
3
-        table.increments('profile_id').primary()
4
-        table.integer('user_id').notNullable()
5
-    })
6
-}
7
-
8
-exports.down = function (knex) {
9
-    return knex.schema.dropTable('profiles')
10
-}

+ 0
- 16
backend/db/migrations/20210527174416_create_response_keys_table.js Dosyayı Görüntüle

@@ -1,16 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('response_keys', function (table) {
3
-        table.increments('response_key_id').primary()
4
-        table.string('response_key_category').notNullable()
5
-        table.string('response_key_prompt')
6
-        table.string('response_key_description')
7
-        table.string('aspect')
8
-        table.string('category')
9
-        table.string('placeholder')
10
-        table.string('invalidInputPrompt')
11
-    })
12
-}
13
-
14
-exports.down = function (knex) {
15
-    return knex.schema.dropTable('response_keys')
16
-}

+ 0
- 12
backend/db/migrations/20210527174422_create_responses_table.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('responses', function (table) {
3
-        table.increments('response_id').primary()
4
-        table.integer('profile_id').notNullable()
5
-        table.integer('response_key_id').notNullable()
6
-        table.specificType('val', 'VARCHAR(1000)')
7
-    })
8
-}
9
-
10
-exports.down = function (knex) {
11
-    return knex.schema.dropTable('responses')
12
-}

+ 0
- 11
backend/db/migrations/20210527174434_create_groupings_table.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('groupings', function (table) {
3
-        table.increments('grouping_id').primary()
4
-        table.string('grouping_name', 128).notNullable()
5
-        table.string('grouping_type', 128).notNullable() // Don't over normalize
6
-    })
7
-}
8
-
9
-exports.down = function (knex) {
10
-    return knex.schema.dropTable('groupings')
11
-}

+ 0
- 14
backend/db/migrations/20210527174440_create_memberships_table.js Dosyayı Görüntüle

@@ -1,14 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('memberships', function (table) {
3
-        table.increments('membership_id').primary()
4
-        table.integer('profile_id').notNullable() // From
5
-        table.integer('grouping_id').notNullable() // To
6
-        table.string('membership_type', 128).notNullable() // Don't over normalize
7
-        table.boolean('can_edit').notNullable()
8
-        table.boolean('is_active').notNullable()
9
-    })
10
-}
11
-
12
-exports.down = function (knex) {
13
-    return knex.schema.dropTable('memberships')
14
-}

+ 0
- 12
backend/db/migrations/20210527174448_create_messages_table.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('messages', function (table) {
3
-        table.increments('message_id').primary()
4
-        table.integer('user_id').notNullable()
5
-        table.integer('grouping_id').notNullable()
6
-        table.string('message', 255).notNullable()
7
-    })
8
-}
9
-
10
-exports.down = function (knex) {
11
-    return knex.schema.dropTable('messages')
12
-}

+ 0
- 14
backend/db/migrations/20210929163630_zipcodes.js Dosyayı Görüntüle

@@ -1,14 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('zip_codes', function (table) {
3
-        table.integer('zip_code_id').primary()
4
-        table.string('latitude', 16).notNullable()
5
-        table.string('longitude', 16).notNullable()
6
-        table.string('city', 128).notNullable()
7
-        table.string('state', 16).notNullable()
8
-        table.string('county', 128).notNullable()
9
-    })
10
-}
11
-
12
-exports.down = function (knex) {
13
-    return knex.schema.dropTable('zip_codes')
14
-}

+ 0
- 12
backend/db/migrations/20211003195015_create_match_queues_table.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('match_queues', function (table) {
3
-        table.increments('match_queue_id').primary()
4
-        table.integer('profile_id').notNullable()
5
-        table.integer('target_id').notNullable()
6
-        table.boolean('is_deleted').notNullable()
7
-    })
8
-}
9
-
10
-exports.down = function (knex) {
11
-    return knex.schema.dropTable('match_queues')
12
-}

+ 0
- 16
backend/db/migrations/20220313230903_create_scores_table.js Dosyayı Görüntüle

@@ -1,16 +0,0 @@
1
-const matrix = require('../generated/prescore_matrix.json')
2
-
3
-exports.up = function (knex) {
4
-    return knex.schema.createTable('prescored_aspects', function (table) {
5
-        table.integer('aspect_id').primary()
6
-        const firstRow = Object.keys(matrix)[0]
7
-        colVals = matrix[firstRow]
8
-        colVals.forEach((col, i) => {
9
-            table.smallint(`${i + 1}`).notNullable()
10
-        })
11
-    })
12
-}
13
-
14
-exports.down = function (knex) {
15
-    return knex.schema.dropTable('prescored_aspects')
16
-}

+ 0
- 13
backend/db/migrations/20220313233557_create_aspects_table.js Dosyayı Görüntüle

@@ -1,13 +0,0 @@
1
-const matrix = require('../generated/prescore_matrix.json')
2
-
3
-exports.up = function (knex) {
4
-    return knex.schema.createTable('aspect_labels', function (table) {
5
-        table.integer('aspect_id').primary()
6
-        table.smallint('a').notNullable()
7
-        table.smallint('b').notNullable()
8
-    })
9
-}
10
-
11
-exports.down = function (knex) {
12
-    return knex.schema.dropTable('aspect_labels')
13
-}

+ 0
- 12
backend/db/migrations/20220403111017_create_tag_descriptions_table.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('tags', function (table) {
3
-        table.increments('tag_id').primary()
4
-        table.string('tag_category', 128).notNullable() // Don't over normalize
5
-        table.string('tag_description', 128).notNullable() // Don't over normalize
6
-        table.boolean('is_active').notNullable()
7
-    })
8
-}
9
-
10
-exports.down = function (knex) {
11
-    return knex.schema.dropTable('tags')
12
-}

+ 0
- 13
backend/db/migrations/20220403111037_create_tag_associations_table.js Dosyayı Görüntüle

@@ -1,13 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('tag_associations', function (table) {
3
-        table.increments('tag_association_id').primary()
4
-        table.integer('profile_id').notNullable()
5
-        table.integer('grouping_id')
6
-        table.integer('tag_id').notNullable()
7
-        table.boolean('is_deleted').notNullable()
8
-    })
9
-}
10
-
11
-exports.down = function (knex) {
12
-    return knex.schema.dropTable('tag_associations')
13
-}

+ 0
- 13
backend/db/migrations/20220403111101_create_user_passwords_table.js Dosyayı Görüntüle

@@ -1,13 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('user_identities', function (table) {
3
-        table.increments('user_pw_id').primary()
4
-        table.integer('user_id').notNullable()
5
-        table.string('uname', 16)
6
-        table.string('pw', 16)
7
-        table.boolean('is_deleted').notNullable()
8
-    })
9
-}
10
-
11
-exports.down = function (knex) {
12
-    return knex.schema.dropTable('user_identities')
13
-}

+ 0
- 12
backend/db/migrations/20220403112041_create_blocked_profiles_table.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('blocked_associations', function (table) {
3
-        table.increments('block_id').primary()
4
-        table.integer('profile_id').notNullable()
5
-        table.integer('profile_id_to_block').notNullable()
6
-        table.boolean('is_active').notNullable()
7
-    })
8
-}
9
-
10
-exports.down = function (knex) {
11
-    return knex.schema.dropTable('blocked_associations')
12
-}

+ 0
- 12
backend/db/migrations/20220901171733_user_authentication.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-exports.up = function (knex) {
2
-    return knex.schema.createTable('authentication', function (table) {
3
-        table.string('user_email', 90).primary().unique()
4
-        table.date('created_at').notNullable()
5
-        // table.char('token').notNullable()
6
-        table.binary('token')
7
-    })
8
-}
9
-
10
-exports.down = function (knex) {
11
-    return knex.schema.dropTable('authentication')
12
-}

+ 0
- 30
backend/db/seeds/01-users.js Dosyayı Görüntüle

@@ -1,30 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-const fs = require('fs')
3
-const dataSort = require ('../dataSort')
4
-const { batchSize } = require('../data-generator/config.json')
5
-
6
-let users = []
7
-const generatedDataPath = './db/generated'
8
-let fileNames = fs.readdirSync(generatedDataPath)
9
-for (let name of fileNames) {
10
-    const data = require(`../generated/${name}`)
11
-    if(name[0] == '_') {
12
-        users = [...users, ...data.users]
13
-    }
14
-}
15
-// sort data
16
-users = dataSort(users, 'user_id')
17
-
18
-exports.seed = async knex => {
19
-    await knex('users').del()
20
-    let usersToPush = []
21
-    let len = users.length
22
-    for (let i = 1; i <= len; i += 1) {
23
-        usersToPush.push(users.shift())
24
-        if (i % batchSize === 0) {
25
-            await knex('users').insert(usersToPush)
26
-            usersToPush = []
27
-        }
28
-        
29
-    }
30
-}

+ 0
- 31
backend/db/seeds/02-profiles.js Dosyayı Görüntüle

@@ -1,31 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-const fs = require('fs')
3
-const dataSort = require('../dataSort')
4
-const { batchSize, ignore } = require('../data-generator/config.json')
5
-
6
-let profiles = []
7
-const generatedDataPath = './db/generated'
8
-let fileNames = fs.readdirSync(generatedDataPath)
9
-for (let name of fileNames) {
10
-    const data = require(`../generated/${name}`)
11
-    if (name[0] == '_') {
12
-        profiles = [...profiles, ...data.profiles]
13
-    }
14
-}
15
-
16
-profiles = dataSort(profiles, 'profile_id').filter(
17
-    profile => !ignore.includes(profile.profile_id),
18
-)
19
-
20
-exports.seed = async knex => {
21
-    await knex('profiles').del()
22
-    let profilesToPush = []
23
-    let len = profiles.length
24
-    for (let i = 1; i <= len; i += 1) {
25
-        profilesToPush.push(profiles.shift())
26
-        if (i % batchSize === 0 || i > profiles.length) {
27
-            await knex('profiles').insert(profilesToPush)
28
-            profilesToPush = []
29
-        }
30
-    }
31
-}

+ 0
- 24
backend/db/seeds/03-response_keys.js Dosyayı Görüntüle

@@ -1,24 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-const fs = require('fs')
3
-
4
-let response_keys = []
5
-const generatedDataPath = './db/generated'
6
-let fileNames = fs.readdirSync(generatedDataPath)
7
-for (let name of fileNames) {
8
-    const data = require(`../generated/${name}`)
9
-    if(name[0] == '_' && data?.response_keys) {
10
-        response_keys = [...response_keys, ...data.response_keys]
11
-    }
12
-}
13
-
14
-exports.seed = function (knex) {
15
-    // Deletes ALL existing entries
16
-    return knex('response_keys')
17
-        .truncate()
18
-        .then(function () {
19
-            // Inserts seed entries
20
-            return response_keys.length > 0
21
-                ? knex('response_keys').insert(response_keys)
22
-                : knex('response_keys').insert(mock.response_keys)
23
-        })
24
-}

+ 0
- 35
backend/db/seeds/04-responses.js Dosyayı Görüntüle

@@ -1,35 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-const fs = require('fs')
3
-const dataSort = require('../dataSort')
4
-const { batchSize, ignore } = require('../data-generator/config.json')
5
-
6
-let responses = []
7
-const generatedDataPath = './db/generated'
8
-let fileNames = fs.readdirSync(generatedDataPath)
9
-for (let name of fileNames) {
10
-    const data = require(`../generated/${name}`)
11
-    if (name[0] == '_') {
12
-        responses = [...responses, ...data.responses]
13
-    }
14
-}
15
-/**
16
- * Prevent seeding responses for
17
- * profile ids so we can test oboarding
18
- */
19
-// responses = dataSort(responses, 'response_id').filter(
20
-// response => !ignore.includes(response.profile_id),
21
-// )
22
-
23
-exports.seed = async knex => {
24
-    await knex('responses').del()
25
-    let responsesToPush = []
26
-    const len = responses.length
27
-    for (let i = 1; i <= len; i += 1) {
28
-        responsesToPush.push(responses.shift())
29
-        // if (i % batchSize === 0 || i > responses.length) {
30
-        // await knex('responses').insert(responsesToPush)
31
-        // responsesToPush = []
32
-        // }
33
-    }
34
-    await knex('responses').insert(responsesToPush)
35
-}

+ 0
- 11
backend/db/seeds/05-memberships.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('memberships')
6
-        .truncate()
7
-        .then(function () {
8
-            // Inserts seed entries
9
-            return knex('memberships').insert(mock.memberships)
10
-        })
11
-}

+ 0
- 11
backend/db/seeds/06-groupings.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('groupings')
6
-        .truncate()
7
-        .then(function () {
8
-            // Inserts seed entries
9
-            return knex('groupings').insert(mock.groupings)
10
-        })
11
-}

+ 0
- 11
backend/db/seeds/07-messages.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('messages')
6
-        .truncate()
7
-        .then(function () {
8
-            // Inserts seed entries
9
-            return knex('messages').insert(mock.messages)
10
-        })
11
-}

+ 0
- 11
backend/db/seeds/08-zipcodes.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const zips = require('../zipcodes')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('zip_codes')
6
-        .truncate()
7
-        .then(function () {
8
-            // Inserts seed entries
9
-            return knex('zip_codes').insert(zips)
10
-        })
11
-}

+ 0
- 10
backend/db/seeds/09-match_queues.js Dosyayı Görüntüle

@@ -1,10 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-exports.seed = function (knex) {
3
-    // Deletes ALL existing entries
4
-    return knex('match_queues')
5
-        .truncate()
6
-        .then(function () {
7
-            // Inserts seed entries
8
-            return knex('match_queues').insert(mock.match_queues)
9
-        })
10
-}

+ 0
- 29
backend/db/seeds/10-scores.js Dosyayı Görüntüle

@@ -1,29 +0,0 @@
1
-const aspects = require('../generated/prescore_matrix.json')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('prescored_aspects')
6
-        .truncate()
7
-        .then(function () {
8
-            let rowCount = 1
9
-            const makeRow = scores => {
10
-                scoreMap = {}
11
-                scores.forEach((score, i) => {
12
-                    scoreMap['aspect_id'] = rowCount
13
-                    scoreMap[i + 1] = score
14
-                })
15
-                return scoreMap
16
-            }
17
-            
18
-            const rows = []
19
-            Object.values(aspects).forEach(rowOfScores => {
20
-                if(Array.isArray(rowOfScores)) {
21
-                    const row = makeRow(rowOfScores)
22
-                    rows.push(row)
23
-                    rowCount++
24
-                }
25
-            })
26
-            // Inserts seed entries
27
-            return knex('prescored_aspects').insert(rows)
28
-        })
29
-}

+ 0
- 25
backend/db/seeds/11-aspects.js Dosyayı Görüntüle

@@ -1,25 +0,0 @@
1
-const aspects = require('../generated/prescore_matrix.json')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('aspect_labels')
6
-        .truncate()
7
-        .then(function () {
8
-            let rowCount = 1
9
-            const rows = []
10
-            Object.keys(aspects).forEach(label => {
11
-                if(label != '_config') {
12
-                    const row = {
13
-                        aspect_id: rowCount
14
-                    }
15
-                    const ab = label.split('-')
16
-                    row.a = parseInt(ab[0])
17
-                    row.b = parseInt(ab[1])
18
-                    rows.push(row)
19
-                    rowCount++
20
-                }
21
-            })
22
-            // Inserts seed entries
23
-            return knex('aspect_labels').insert(rows)
24
-        })
25
-}

+ 0
- 11
backend/db/seeds/12-tags.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('tags')
6
-        .truncate()
7
-        .then(function () {
8
-            // Inserts seed entries
9
-            return knex('tags').insert(mock.tags)
10
-        })
11
-}

+ 0
- 11
backend/db/seeds/13-tag_associations.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const mock = require('../data-generator/mock')
2
-
3
-exports.seed = function (knex) {
4
-    // Deletes ALL existing entries
5
-    return knex('tag_associations')
6
-        .truncate()
7
-        .then(function () {
8
-            // Inserts seed entries
9
-            return knex('tag_associations').insert(mock.tag_associations)
10
-        })
11
-}

+ 0
- 265
backend/db/survey-generator.js Dosyayı Görüntüle

@@ -1,265 +0,0 @@
1
-const fs = require('fs')
2
-const similarity = require('compute-cosine-similarity')
3
-const config = require('./data-generator/config.js')
4
-
5
-const magic = config.magic // Multiply cosine similary by this
6
-
7
-const not_important = config.scoreVals[0]
8
-const somewhat_important = config.scoreVals[1]
9
-const important = config.scoreVals[2]
10
-const very_important = config.scoreVals[3]
11
-const extremely_important = config.scoreVals[4]
12
-const mandatory = config.scoreVals[5]
13
-
14
-// -
15
-// 1440 - 2400 total range
16
-// 1440 - 1900 limited range
17
-// -
18
-// Reserved for REALLY important answers
19
-// like full-time vs part-time
20
-// and remote vs onsite only
21
-// 400 mandatory
22
-
23
-const importance = [
24
-    not_important,
25
-    somewhat_important,
26
-    important,
27
-    very_important,
28
-    extremely_important,
29
-]
30
-
31
-const langs = [
32
-    'javascript',
33
-    'python',
34
-    'ruby',
35
-    'erlang',
36
-    'haskall',
37
-    'php',
38
-    'swift',
39
-    'rust',
40
-    'objective-c',
41
-    'common lisp',
42
-    'java',
43
-    'perl',
44
-    'cobol',
45
-    'fortran',
46
-    'julia',
47
-    'c#',
48
-    'go',
49
-    'c++',
50
-]
51
-const duration = ['full', 'part']
52
-const location = ['onsite', 'remote', 'flexible']
53
-
54
-const otherWeightLookup = {
55
-    full: mandatory,
56
-    part: mandatory,
57
-    onsite: mandatory,
58
-    remote: mandatory,
59
-    flexible: mandatory,
60
-}
61
-const rand = max => {
62
-    return Math.floor(Math.random() * max) < 1
63
-        ? 1
64
-        : Math.floor(Math.random() * max)
65
-}
66
-
67
-class DummyProfile {
68
-    constructor() {
69
-        this.id = null
70
-        this.profileResponses = null
71
-        this.langPref = null
72
-        this.durationPref = null
73
-        this.locationPref = null
74
-
75
-        this.shouldDelete = false
76
-
77
-        // profile is constructed of 12 answers, 2 for each dimension
78
-        this.profileResponses = this.getRandomAnswers(12, importance)
79
-        this.langPref = this.getRandomAnswers(rand(4), langs)
80
-        this.durationPref = this.getRandomAnswers(1, duration)
81
-        this.locationPref = this.getRandomAnswers(1, location)
82
-
83
-        this.matchPref = null
84
-
85
-        this.candidateIndex = 0
86
-        this.otp = null
87
-        this.forder = []
88
-    }
89
-    clearPlaceholderMatches() {
90
-        this.matchPref = this.matchPref.filter(
91
-            match => match.shouldDelete == false,
92
-        )
93
-        this.forder = this.forder.filter(
94
-            potentialFiance => potentialFiance.shouldDelete == false,
95
-        )
96
-        if (this.otp.shouldDelete) {
97
-            this.otp = null
98
-        }
99
-        // console.log(this.matchPref)
100
-    }
101
-    rank(p) {
102
-        for (let i = 0; i < this.matchPref.length; i++)
103
-            if (this.matchPref[i] === p) return i
104
-        return this.matchPref.length + 1
105
-    }
106
-    prefers(p) {
107
-        return this.rank(p) < this.rank(this.otp)
108
-    }
109
-    nextCandidate() {
110
-        if (this.candidateIndex >= this.matchPref.length) return null
111
-        return this.matchPref[this.candidateIndex++]
112
-    }
113
-    engageTo(p) {
114
-        if (p.otp) p.otp.otp = null
115
-        p.otp = this
116
-        p.forder.unshift(this)
117
-        if (this.otp) this.otp.otp = null
118
-        this.otp = p
119
-        this.forder.unshift(p)
120
-    }
121
-    // My stuff
122
-    getRandomAnswers(count, options) {
123
-        const answers = []
124
-        for (let i = 0; i < count; i++) {
125
-            const random = rand(options.length)
126
-            answers.push(options[random])
127
-        }
128
-        return answers
129
-    }
130
-}
131
-
132
-function engageEveryone(guys) {
133
-    var done
134
-    do {
135
-        done = true
136
-        guys.forEach(guy => {
137
-            if (!guy.otp) {
138
-                done = false
139
-                const gal = guy.nextCandidate()
140
-                if (!gal.otp || gal.prefers(guy)) guy.engageTo(gal)
141
-            }
142
-        })
143
-    } while (!done)
144
-}
145
-const generateDummyProfiles = (count, startFrom) => {
146
-    const profiles = []
147
-    for (let i = 0; i < count; i++) {
148
-        const dummyProfile = new DummyProfile()
149
-        dummyProfile.id = startFrom + i + 1
150
-        profiles.push(dummyProfile)
151
-    }
152
-    profiles.forEach(dummy => {
153
-        dummy.profileResponses = dummy.profileResponses.map(
154
-            (answer, response_key_id) => {
155
-                const answerObj = {}
156
-                // aka: id for the question we asked
157
-                answerObj[response_key_id] = answer
158
-                return answerObj
159
-            },
160
-        )
161
-    })
162
-    return profiles
163
-}
164
-
165
-const generatedSeekers = generateDummyProfiles(20, 0)
166
-const generatedProviders = generateDummyProfiles(5, generatedSeekers.length)
167
-const balanceSeekersAndProviders = (seekers, providers) => {
168
-    let diff = 0
169
-    let smallerList = null
170
-
171
-    if (seekers.length < providers.length) {
172
-        diff = providers.length - seekers.length
173
-        smallerList = seekers
174
-    } else {
175
-        diff = seekers.length - providers.length
176
-        smallerList = providers
177
-    }
178
-    let fillerId = seekers.length + providers.length
179
-    for (let i = 0; i < diff; i++) {
180
-        const filler = new DummyProfile()
181
-        filler.id = fillerId + i + 1
182
-        filler.profileResponses = filler.profileResponses.map(
183
-            (answer, response_key_id) => {
184
-                const answerObj = {}
185
-                // aka: id for the question we asked
186
-                answerObj[response_key_id] = answer
187
-                return answerObj
188
-            },
189
-        )
190
-        filler.shouldDelete = true
191
-        smallerList.push(filler)
192
-    }
193
-}
194
-
195
-const scoreMatch = (seeker, potentialMatch) => {
196
-    const seekerResponseValues = seeker.profileResponses.map(res =>
197
-        parseInt(Object.values(res)),
198
-    )
199
-    const potentialMatchResponseValues = potentialMatch.profileResponses.map(
200
-        res => parseInt(Object.values(res)),
201
-    )
202
-    return Math.floor(
203
-        similarity(seekerResponseValues, potentialMatchResponseValues) * magic,
204
-    )
205
-}
206
-const compareProfile = (seeker, unorderedPotentialMatches) => {
207
-    const scored = unorderedPotentialMatches
208
-        .map(potentialMatch => {
209
-            // add the match to object keyed by score
210
-            return {
211
-                profileMatchScore: scoreMatch(seeker, potentialMatch),
212
-                profile: potentialMatch,
213
-            }
214
-        })
215
-        .sort((a, b) => a.profileMatchScore - b.profileMatchScore)
216
-    // return ordered by score
217
-    return scored.map(profileScore => profileScore.profile)
218
-}
219
-
220
-balanceSeekersAndProviders(generatedSeekers, generatedProviders)
221
-
222
-// Score
223
-generatedSeekers.forEach(seeker => {
224
-    seeker.matchPref = compareProfile(seeker, generatedProviders)
225
-})
226
-generatedProviders.forEach(provider => {
227
-    provider.matchPref = compareProfile(provider, generatedSeekers)
228
-})
229
-
230
-// Everything balanced ready for stable marriage
231
-if (generatedSeekers.length == generatedProviders.length) {
232
-    engageEveryone(generatedProviders)
233
-    generatedSeekers.forEach(seeker => seeker.clearPlaceholderMatches())
234
-    generatedProviders.forEach(provider => provider.clearPlaceholderMatches())
235
-
236
-    console.log('\nuser:', generatedProviders[0].id, '| provider')
237
-    console.log(
238
-        'otp',
239
-        generatedProviders[0].otp ? generatedProviders[0].otp.id : null,
240
-        'rank',
241
-        generatedProviders[0].otp
242
-            ? generatedProviders[0].matchPref
243
-                  .map(m => m.id)
244
-                  .indexOf(generatedProviders[0].otp.id) + 1
245
-            : generatedProviders[0].otp,
246
-    )
247
-    // console.log(generatedProviders[0].matchPref.map(m => m.id))
248
-    console.log(generatedProviders[0])
249
-
250
-    console.log('---')
251
-
252
-    console.log('user:', generatedSeekers[0].id, '| seeker')
253
-    console.log(
254
-        'otp',
255
-        generatedSeekers[0].otp ? generatedSeekers[0].otp.id : null,
256
-        'rank',
257
-        generatedSeekers[0].otp
258
-            ? generatedSeekers[0].matchPref
259
-                  .map(m => m.id)
260
-                  .indexOf(generatedSeekers[0].otp.id) + 1
261
-            : generatedSeekers[0].otp,
262
-    )
263
-    console.log(generatedSeekers[0])
264
-    // console.log(generatedSeekers[0].matchPref.map(m => m.id))
265
-}

+ 0
- 341930
backend/db/zipcodes.js
Dosya farkı çok büyük olduğundan ihmal edildi
Dosyayı Görüntüle


+ 0
- 73
backend/lib/auth/strategies/jwt.js Dosyayı Görüntüle

@@ -1,73 +0,0 @@
1
-'use strict'
2
-const JWT = require('jsonwebtoken')
3
-const crypto = require('crypto')
4
-
5
-const hashToken = async token => {
6
-    const salt = process.env.APP_SESSION_SALT
7
-    try {
8
-        return crypto.createHmac('sha256', salt).update(token).digest('hex')
9
-    } catch (err) {
10
-        throw new Error(err.message)
11
-    }
12
-}
13
-
14
-const createToken = (data, expiration = 600) => {
15
-    const key = process.env.APP_SECRET
16
-    const obj = {}
17
-
18
-    Object.assign(obj, { ...data })
19
-    return JWT.sign(obj, key, { expiresIn: expiration })
20
-}
21
-
22
-const validateToken = token => {
23
-    const key = process.env.APP_SECRET
24
-    try {
25
-        return JWT.verify(token, key)
26
-    } catch (err) {
27
-        return { payload: null, message: err.message }
28
-    }
29
-}
30
-
31
-module.exports = options => {
32
-    return {
33
-        key: options.jwtKey,
34
-        verifyOptions: {
35
-            algorithms: ['HS256'],
36
-        },
37
-        // TODO: Naming conventions need to be reversed again??
38
-        validate: async (decoded, request, h) => {
39
-            const sessionTokenFromHeaders = request.headers.authorization
40
-            const hashedSessionTokenFromHeaders = await hashToken(
41
-                sessionTokenFromHeaders,
42
-            )
43
-            const activeSession =
44
-                request.server.app.activeSessions[hashedSessionTokenFromHeaders]
45
-            if (!activeSession)
46
-                throw new Error(
47
-                    `No session found for ${hashedSessionTokenFromHeaders}`,
48
-                )
49
-
50
-            const sessionToken = activeSession.sessionToken
51
-            const accessToken = activeSession.accessToken
52
-            const validatedSessionToken = validateToken(sessionToken)
53
-            const validatedAccessToken = validateToken(accessToken)
54
-            if (!validatedAccessToken.payload) {
55
-                console.log('accessToken no longer valid, reissuing... ')
56
-                activeSession.accessToken = createToken(
57
-                    { payload: validatedSessionToken.payload },
58
-                    // NOTE: Expiration of new sessionToken set for 200 seconds (testing)
59
-                    100,
60
-                )
61
-            }
62
-            try {
63
-                const validatedJwt = JWT.verify(
64
-                    sessionToken,
65
-                    process.env.APP_SECRET,
66
-                )
67
-                return { isValid: true, credentials: validatedJwt.email }
68
-            } catch (err) {
69
-                return { isValid: false, error: err.message }
70
-            }
71
-        },
72
-    }
73
-}

+ 0
- 32
backend/lib/index.js Dosyayı Görüntüle

@@ -1,10 +1,4 @@
1 1
 const UserPlugin = require('./plugins/user')
2
-const MembershipPlugin = require('./plugins/membership')
3
-const SurveyPlugin = require('./plugins/survey')
4
-const ProfilePlugin = require('./plugins/profile')
5
-const NotificationPlugin = require('./plugins/notification')
6
-const HealthPlugin = require('./plugins/health')
7
-const FilterPlugin = require('./plugins/filter')
8 2
 
9 3
 /**
10 4
  * A Hapi server instance
@@ -29,31 +23,5 @@ exports.plugin = {
29 23
         await server.register(UserPlugin, {
30 24
             routes: { prefix: '/user' },
31 25
         })
32
-
33
-        await server.register(MembershipPlugin, {
34
-            routes: { prefix: '/membership' },
35
-        })
36
-
37
-        await server.register(SurveyPlugin, {
38
-            routes: {
39
-                prefix: '/survey',
40
-            },
41
-        })
42
-
43
-        await server.register(ProfilePlugin, {
44
-            routes: { prefix: '/profile' },
45
-        })
46
-
47
-        await server.register(NotificationPlugin, {
48
-            routes: { prefix: '/notification' },
49
-        })
50
-
51
-        await server.register(HealthPlugin, {
52
-            routes: { prefix: '/health' },
53
-        })
54
-
55
-        await server.register(FilterPlugin, {
56
-            routes: { prefix: '/filter' },
57
-        })
58 26
     },
59 27
 }

+ 0
- 18
backend/lib/models/aspect.js Dosyayı Görüntüle

@@ -1,18 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3
-const config = require('../../db/data-generator/config.json')
4
-
5
-const aspects = { aspect_id: Joi.number() }
6
-const possible_combinations = Math.pow(config.scoreVals.length, 2)
7
-for(let i = 1; i <= possible_combinations; i++) {
8
-    aspects[i] = Joi.number()
9
-}
10
-
11
-module.exports = class Aspect extends Schwifty.Model {
12
-    static get tableName() {
13
-        return 'prescored_aspects'
14
-    }
15
-    static get joiSchema() {
16
-        return Joi.object(aspects)
17
-    }
18
-}

+ 0
- 15
backend/lib/models/aspect_label.js Dosyayı Görüntüle

@@ -1,15 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3
-
4
-module.exports = class AspectLabel extends Schwifty.Model {
5
-    static get tableName() {
6
-        return 'aspect_labels'
7
-    }
8
-    static get joiSchema() {
9
-        return Joi.object({ 
10
-            aspect_id: Joi.number(),
11
-            a: Joi.string(),
12
-            b: Joi.string()
13
-        })
14
-    }
15
-}

+ 0
- 12
backend/lib/models/authentication.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3
-const { userAuth } = require('../schemas/authentication')
4
-
5
-module.exports = class Auth extends Schwifty.Model {
6
-    static get tableName() {
7
-        return 'authentication'
8
-    }
9
-    static get joiSchema() {
10
-        return userAuth
11
-    }
12
-}

+ 0
- 28
backend/lib/models/grouping.js Dosyayı Görüntüle

@@ -1,28 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const groupingSchema = require('../schemas/groupings')
3
-const Profile = require('./profile')
4
-
5
-module.exports = class Grouping extends Schwifty.Model {
6
-    static get tableName() {
7
-        return 'groupings'
8
-    }
9
-    static get relationMappings() {
10
-        return {
11
-            profiles: {
12
-                relation: Schwifty.Model.ManyToManyRelation,
13
-                modelClass: Profile,
14
-                join: {
15
-                    from: 'groupings.grouping_id',
16
-                    through: {
17
-                        from: 'memberships.grouping_id',
18
-                        to: 'memberships.profile_id'
19
-                    },
20
-                    to: 'profiles.profile_id'
21
-                },
22
-            },
23
-        }
24
-    }
25
-    static get joiSchema() {
26
-        return groupingSchema.single
27
-    }
28
-}

+ 0
- 28
backend/lib/models/matchqueue.js Dosyayı Görüntüle

@@ -1,28 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const User = require('./user')
3
-const queueSchema = require('../schemas/queues')
4
-
5
-module.exports = class MatchQueue extends Schwifty.Model {
6
-    static get tableName() {
7
-        return 'match_queues'
8
-    }
9
-    static get relationMappings() {
10
-        return {
11
-            user: {
12
-                relation: Schwifty.Model.HasOneThroughRelation,
13
-                modelClass: User,
14
-                join: {
15
-                    from: 'match_queues.target_id',
16
-                    through: {
17
-                        from: 'profiles.profile_id',
18
-                        to: 'profiles.user_id',
19
-                    },
20
-                    to: 'users.user_id',
21
-                },
22
-            },
23
-        }
24
-    }
25
-    static get joiSchema() {
26
-        return queueSchema.single
27
-    }
28
-}

+ 0
- 11
backend/lib/models/membership.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const membershipSchema = require('../schemas/memberships')
3
-
4
-module.exports = class Membership extends Schwifty.Model {
5
-    static get tableName() {
6
-        return 'memberships'
7
-    }
8
-    static get joiSchema() {
9
-        return membershipSchema.single
10
-    }
11
-}

+ 0
- 13
backend/lib/models/message.js Dosyayı Görüntüle

@@ -1,13 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3
-
4
-module.exports = class Message extends Schwifty.Model {
5
-    static get tableName() {
6
-        return 'messages'
7
-    }
8
-    static get joiSchema() {
9
-        return Joi.object({
10
-            message_id: Joi.number().required(),
11
-        })
12
-    }
13
-}

+ 0
- 45
backend/lib/models/profile.js Dosyayı Görüntüle

@@ -1,45 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3
-const TagAssociation = require('./tag-association')
4
-const Response = require('./response')
5
-const User = require('./user')
6
-
7
-module.exports = class Profile extends Schwifty.Model {
8
-    static get tableName() {
9
-        return 'profiles'
10
-    }
11
-    static get relationMappings() {
12
-        return {
13
-            tags: {
14
-                relation: Schwifty.Model.HasManyRelation,
15
-                modelClass: TagAssociation,
16
-                join: {
17
-                    from: 'tag_associations.profile_id',
18
-                    to: 'profiles.profile_id',
19
-                },
20
-            },
21
-            responses: {
22
-                relation: Schwifty.Model.HasManyRelation,
23
-                modelClass: Response,
24
-                join: {
25
-                    from: 'responses.profile_id',
26
-                    to: 'profiles.profile_id',
27
-                },
28
-            },
29
-            user: {
30
-                relation: Schwifty.Model.BelongsToOneRelation,
31
-                modelClass: User,
32
-                join: {
33
-                    from: 'users.user_id',
34
-                    to: 'profiles.user_id',
35
-                },
36
-            },
37
-        }
38
-    }
39
-    static get joiSchema() {
40
-        return Joi.object({
41
-            profile_id: Joi.number(),
42
-            user_id: Joi.number(),
43
-        })
44
-    }
45
-}

+ 0
- 12
backend/lib/models/response-key.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3
-const surveyResponseSchema = require('../schemas/responses')
4
-
5
-module.exports = class ResponseKey extends Schwifty.Model {
6
-    static get tableName() {
7
-        return 'response_keys'
8
-    }
9
-    static get joiSchema() {
10
-        return surveyResponseSchema.key
11
-    }
12
-}

+ 0
- 11
backend/lib/models/response.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const responseSchema = require('../schemas/responses')
3
-
4
-module.exports = class Response extends Schwifty.Model {
5
-    static get tableName() {
6
-        return 'responses'
7
-    }
8
-    static get joiSchema() {
9
-        return responseSchema.single
10
-    }
11
-}

+ 0
- 25
backend/lib/models/tag-association.js Dosyayı Görüntüle

@@ -1,25 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-
3
-const tagSchema = require('../schemas/tags')
4
-const Tag = require('./tag')
5
-
6
-module.exports = class TagAssociation extends Schwifty.Model {
7
-    static get tableName() {
8
-        return 'tag_associations'
9
-    }
10
-    static get relationMappings() {
11
-        return {
12
-            description: {
13
-                relation: Schwifty.Model.BelongsToOneRelation,
14
-                modelClass: Tag,
15
-                join: {
16
-                    from: 'tag_associations.tag_id',
17
-                    to: 'tags.tag_id',
18
-                },
19
-            },
20
-        }
21
-    }
22
-    static get joiSchema() {
23
-        return tagSchema.association
24
-    }
25
-}

+ 0
- 11
backend/lib/models/tag.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const tagSchema = require('../schemas/tags')
3
-
4
-module.exports = class Tag extends Schwifty.Model {
5
-    static get tableName() {
6
-        return 'tags'
7
-    }
8
-    static get joiSchema() {
9
-        return tagSchema.single
10
-    }
11
-}

+ 5
- 9
backend/lib/models/user.js Dosyayı Görüntüle

@@ -1,18 +1,14 @@
1
+const { single } = require('../schemas/user')
1 2
 const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3 3
 
4
+/**
5
+ * @typedef User
6
+ */
4 7
 module.exports = class User extends Schwifty.Model {
5 8
     static get tableName() {
6 9
         return 'users'
7 10
     }
8 11
     static get joiSchema() {
9
-        return Joi.object({
10
-            user_id: Joi.number(),
11
-            user_name: Joi.string(),
12
-            user_email: Joi.string().required(),
13
-            is_poster: Joi.number().required(),
14
-            is_admin: Joi.number().required(),
15
-            is_verified: Joi.number().required(),
16
-        })
12
+        return single
17 13
     }
18 14
 }

+ 0
- 18
backend/lib/models/zip-code.js Dosyayı Görüntüle

@@ -1,18 +0,0 @@
1
-const Schwifty = require('@hapipal/schwifty')
2
-const Joi = require('joi')
3
-
4
-module.exports = class ZipCode extends Schwifty.Model {
5
-    static get tableName() {
6
-        return 'zip_codes'
7
-    }
8
-    static get joiSchema() {
9
-        return Joi.object({
10
-            zip_code_id: Joi.number(),
11
-            latitude: Joi.string().required(),
12
-            longitude: Joi.string().required(),
13
-            city: Joi.string().required(),
14
-            state: Joi.string().required(),
15
-            county: Joi.string().required(),
16
-        })
17
-    }
18
-}

+ 0
- 13
backend/lib/plugins/filter.js Dosyayı Görüntüle

@@ -1,13 +0,0 @@
1
-const Schmervice = require('@hapipal/schmervice')
2
-const FilterRoute = require('../routes/filter/get')
3
-const FilterService = require('../services/filter')
4
-
5
-module.exports = {
6
-    name: 'filter-plugin',
7
-    version: '1.0.0',
8
-    register: async (server, options) => {
9
-        await server.register(Schmervice)
10
-        await server.registerService(FilterService)
11
-        await server.route(FilterRoute)
12
-    },
13
-}

+ 0
- 9
backend/lib/plugins/health.js Dosyayı Görüntüle

@@ -1,9 +0,0 @@
1
-const HealthRoute = require('../routes/health/get')
2
-
3
-module.exports = {
4
-    name: 'health-plugin',
5
-    version: '1.0.0',
6
-    register: async (server, options) => {
7
-        await server.route(HealthRoute)
8
-    },
9
-}

+ 0
- 35
backend/lib/plugins/membership.js Dosyayı Görüntüle

@@ -1,35 +0,0 @@
1
-const Objection = require('objection')
2
-const Schmervice = require('@hapipal/schmervice')
3
-
4
-const GroupingModel = require('../models/grouping')
5
-const MembershipModel = require('../models/membership')
6
-
7
-const MembershipService = require('../services/membership')
8
-
9
-const MembershipJoinRoute = require('../routes/membership/join')
10
-const MembershipLeaveRoute = require('../routes/membership/leave')
11
-const MembershipActiveRoute = require('../routes/membership/active')
12
-const MembershipRevealRoute = require('../routes/membership/reveal')
13
-
14
-module.exports = {
15
-    name: 'membership-plugin',
16
-    version: '1.0.0',
17
-    register: async (server, options) => {
18
-        await server.registerModel(GroupingModel)
19
-        await server.registerModel(MembershipModel)
20
-
21
-        // Bind to global context
22
-        // So we can use Objection transactions
23
-        server.bind({
24
-            transaction: fn => Objection.transaction(server.knex(), fn),
25
-        })
26
-
27
-        await server.register(Schmervice)
28
-        server.registerService(MembershipService)
29
-
30
-        await server.route(MembershipJoinRoute)
31
-        await server.route(MembershipLeaveRoute)
32
-        await server.route(MembershipActiveRoute)
33
-        await server.route(MembershipRevealRoute)
34
-    },
35
-}

+ 0
- 119
backend/lib/plugins/notification.js Dosyayı Görüntüle

@@ -1,119 +0,0 @@
1
-const _allStreams = {}
2
-
3
-const NotificationRoute = require('../routes/notification')
4
-
5
-/** Heavily lifted from: https://github.com/mtharrison/susie/blob/master/lib/index.js */
6
-
7
-const Stream = require('stream')
8
-const PassThrough = Stream.PassThrough
9
-const Transform = Stream.Transform
10
-
11
-const ENDER = { event: 'end', data: '' }
12
-
13
-/**
14
- * Stringify a stream
15
- * ?: I don't really get what this is doing
16
- * @param {Stream} event
17
- * @returns {string}
18
- */
19
-const _stringifyEvent = function (event) {
20
-    let str = ''
21
-    const endl = '\r\n'
22
-    for (const i in event) {
23
-        let val = event[i]
24
-        if (val instanceof Buffer) {
25
-            val = val.toString()
26
-        }
27
-        if (typeof val === 'object') {
28
-            val = JSON.stringify(val)
29
-        }
30
-        str += i + ': ' + val + endl
31
-    }
32
-    str += endl
33
-    return str
34
-}
35
-
36
-/**
37
- * Transform extension
38
- * ?: I don't really get what this is doing
39
- * @param {object} options
40
- * @param {object} objectMode
41
- */
42
-class Transformer extends Transform {
43
-    constructor(options, objectMode) {
44
-        super({ objectMode })
45
-        options = options || {}
46
-        this.counter = 1
47
-        this.event = options.event || null
48
-        this.generateId = options.generateId
49
-            ? options.generateId
50
-            : () => this.counter++
51
-    }
52
-    _transform(chunk, encoding, callback) {
53
-        const event = {
54
-            id: this.generateId(chunk),
55
-            data: chunk,
56
-        }
57
-        if (this.event) {
58
-            event.event = this.event
59
-        }
60
-        this.push(_stringifyEvent(event))
61
-        callback()
62
-    }
63
-    _flush(callback) {
64
-        this.push(_stringifyEvent(ENDER))
65
-        callback()
66
-    }
67
-}
68
-
69
-/**
70
- * Callback to decorate server toolkit (h)
71
- * !: Currently we only support ObjectMode streams
72
- * ?: I don't really get what this is doing
73
- * @param {Stream} event stream input
74
- * @param {Toolkit} h hapi common response toolkit
75
- * @param {object} streamOptions
76
- */
77
-const _event = (event, h, streamOptions) => {
78
-    let active
79
-    if (event instanceof Stream.Readable) {
80
-        if (event._readableState.objectMode) {
81
-            active = new PassThrough()
82
-            const through = new Transformer(streamOptions, true)
83
-            through.pipe(active)
84
-            event.pipe(through)
85
-        }
86
-        return h
87
-            .response(active)
88
-            .header('content-type', 'text/event-stream')
89
-            .header('content-encoding', 'identity')
90
-    }
91
-}
92
-
93
-/**
94
- * Takes an open HTTP stream and writes
95
- * a msg to it, then fires notification plugin's
96
- * _event callback
97
- * @param {object} msg you want to send
98
- * @param {string} name <profileId>.<eventType>
99
- * @param {boolean} shouldInitialize
100
- * @param {Toolkit} h hapi common response toolkit
101
- */
102
-const onNotify = (name, msg, h, shouldInitialize = false) => {
103
-    if (shouldInitialize) {
104
-        _allStreams[name] = new PassThrough({ objectMode: true })
105
-    }
106
-    if (!_allStreams[name]) return
107
-    _allStreams[name].write(msg)
108
-
109
-    return _event(_allStreams[name], h, { event: name })
110
-}
111
-
112
-module.exports = {
113
-    name: 'notification-plugin',
114
-    version: '1.0.0',
115
-    register: async server => {
116
-        await server.route(NotificationRoute)
117
-        server.method('notify', onNotify)
118
-    },
119
-}

+ 0
- 63
backend/lib/plugins/profile.js Dosyayı Görüntüle

@@ -1,63 +0,0 @@
1
-const Objection = require('objection')
2
-const Schmervice = require('@hapipal/schmervice')
3
-
4
-const ProfileModel = require('../models/profile')
5
-const TagModel = require('../models/tag')
6
-const TagAssociationModel = require('../models/tag-association')
7
-const AspectModel = require('../models/aspect')
8
-const AspectLabelModel = require('../models/aspect_label')
9
-const ResponseModel = require('../models/response')
10
-const ZipCodeModel = require('../models/zip-code')
11
-const MatchQueueModel = require('../models/matchqueue')
12
-
13
-const ProfileService = require('../services/profile')
14
-const MatchQueueService = require('../services/matchqueue')
15
-const MatchService = require('../services/match')
16
-
17
-const ProfileScoreRoute = require('../routes/profile/score')
18
-const ProfileUpdateRoute = require('../routes/profile/update')
19
-const ProfileInsertRoute = require('../routes/profile/insert')
20
-const ProfileRespondRoute = require('../routes/profile/respond')
21
-const ProfileMatchRoute = require('../routes/profile/match')
22
-const ProfileQueueRoute = require('../routes/profile/queue')
23
-const ProfileGetRoute = require('../routes/profile/get')
24
-const ProfilePatchQueueRoute = require('../routes/profile/patch-queue')
25
-const TagRevealRoute = require('../routes/tag/reveal')
26
-const TagGetRoute = require('../routes/tag/get')
27
-
28
-module.exports = {
29
-    name: 'profile-plugin',
30
-    version: '1.0.0',
31
-    register: async (server, options) => {
32
-        await server.registerModel(ProfileModel)
33
-        await server.registerModel(TagModel)
34
-        await server.registerModel(TagAssociationModel)
35
-        await server.registerModel(AspectModel)
36
-        await server.registerModel(AspectLabelModel)
37
-        await server.registerModel(ResponseModel)
38
-        await server.registerModel(ZipCodeModel)
39
-        await server.registerModel(MatchQueueModel)
40
-
41
-        // Bind to global context
42
-        // So we can use Objection transactions
43
-        server.bind({
44
-            transaction: fn => Objection.transaction(server.knex(), fn),
45
-        })
46
-
47
-        await server.register(Schmervice)
48
-        await server.registerService(ProfileService)
49
-        await server.registerService(MatchQueueService)
50
-        await server.registerService(MatchService)
51
-
52
-        await server.route(ProfileScoreRoute)
53
-        await server.route(ProfileRespondRoute)
54
-        await server.route(ProfileUpdateRoute)
55
-        await server.route(ProfileInsertRoute)
56
-        await server.route(ProfileMatchRoute)
57
-        await server.route(ProfileQueueRoute)
58
-        await server.route(ProfileGetRoute)
59
-        await server.route(ProfilePatchQueueRoute)
60
-        await server.route(TagRevealRoute)
61
-        await server.route(TagGetRoute)
62
-    },
63
-}

+ 0
- 28
backend/lib/plugins/survey.js Dosyayı Görüntüle

@@ -1,28 +0,0 @@
1
-const Objection = require('objection')
2
-const Schmervice = require('@hapipal/schmervice')
3
-
4
-const ReponseKeyModel = require('../models/response-key')
5
-
6
-const ResponseService = require('../services/response')
7
-
8
-const ResponseQuestionsRoute = require('../routes/survey/questions')
9
-
10
-module.exports = {
11
-    name: 'survey-plugin',
12
-    version: '1.0.0',
13
-    register: async (server, options) => {
14
-        await server.registerModel(ReponseKeyModel)
15
-
16
-        // Bind to global context
17
-        // So we can use Objection transactions
18
-        server.bind({
19
-            transaction: fn => Objection.transaction(server.knex(), fn),
20
-        })
21
-
22
-        await server.register(Schmervice)
23
-        server.registerService(ResponseService)
24
-
25
-        await server.route(ResponseQuestionsRoute)
26
-    },
27
-    models: { ReponseKeyModel },
28
-}

+ 3
- 35
backend/lib/plugins/user.js Dosyayı Görüntüle

@@ -1,40 +1,18 @@
1 1
 const Objection = require('objection')
2 2
 const Schmervice = require('@hapipal/schmervice')
3 3
 const Schwifty = require('@hapipal/schwifty')
4
-const Jwt = require('hapi-auth-jwt2')
5
-const JwtStrategy = require('../auth/strategies/jwt')
6 4
 
7 5
 const UserModel = require('../models/user')
8
-const AuthModel = require('../models/authentication')
9
-
10
-const UserProfileCreateRoute = require('../routes/user/create-profile')
11
-const UserLoginRoute = require('../routes/user/login')
12
-const UserSignupRoute = require('../routes/user/signup')
13
-const UserEmailRoute = require('../routes/user/send-email.js')
14
-const UserVerifyActiveRoute = require('../routes/user/verify-session.js')
15
-const UserCreateTokenRoute = require('../routes/user/token.js')
16
-const UserValidateSessionRoute = require('../routes/user/validate-session.js')
17
-const UserRemoveSessionRoute = require('../routes/user/remove-session.js')
18
-const UserPassword = require('../routes/user/authentication')
19
-
20 6
 const UserService = require('../services/user')
21
-const DisplayService = require('../services/display')
22
-const HealthService = require('../services/health')
7
+
8
+const GetUser = require('../routes/user/get-user')
23 9
 
24 10
 module.exports = {
25 11
     name: 'user-plugin',
26 12
     version: '1.0.0',
27 13
     register: async (server, options) => {
28
-        await server.register(Jwt)
29 14
         await server.register(Schwifty)
30 15
         await server.registerModel(UserModel)
31
-        await server.registerModel(AuthModel)
32
-
33
-        const mainApp = server.registrations['main-app-plugin']
34
-        const jwtOptions = JwtStrategy(mainApp.options)
35
-
36
-        server.auth.strategy('default_jwt', 'jwt', jwtOptions)
37
-        server.auth.default('default_jwt')
38 16
 
39 17
         // Bind to global context
40 18
         // So we can use Objection transactions
@@ -44,17 +22,7 @@ module.exports = {
44 22
 
45 23
         await server.register(Schmervice)
46 24
         server.registerService(UserService)
47
-        server.registerService(DisplayService)
48
-        server.registerService(HealthService)
49 25
 
50
-        await server.route(UserLoginRoute)
51
-        await server.route(UserSignupRoute)
52
-        await server.route(UserProfileCreateRoute)
53
-        await server.route(UserEmailRoute)
54
-        await server.route(UserVerifyActiveRoute)
55
-        await server.route(UserCreateTokenRoute)
56
-        await server.route(UserValidateSessionRoute)
57
-        await server.route(UserRemoveSessionRoute)
58
-        await server.route(UserPassword)
26
+        await server.route(GetUser)
59 27
     },
60 28
 }

+ 0
- 89
backend/lib/routes/filter/get.js Dosyayı Görüntüle

@@ -1,89 +0,0 @@
1
-'use strict'
2
-
3
-// NOTE: Current Implementation does not require this route
4
-// (see Auth.vue in components/onboarding and queue route with filter.js)
5
-const Joi = require('joi')
6
-const apiSchema = require('../../schemas/api')
7
-const errorSchema = require('../../schemas/errors')
8
-const filterSchema = require('../../schemas/filter')
9
-const profileSchema = require('../../schemas/profiles')
10
-
11
-const pluginConfig = {
12
-    handlerType: 'filter',
13
-    docs: {
14
-        description: 'Filter match pool',
15
-        notes: 'Returns filtered subset of match pool',
16
-    },
17
-}
18
-
19
-const validators = {
20
-    query: Joi.object({
21
-        match_pool: Joi.array().items(profileSchema.single),
22
-        distance: Joi.string(),
23
-        presence: Joi.string(),
24
-    }),
25
-}
26
-
27
-const responseSchemas = {
28
-    filteredMatchPool: filterSchema.matchPool, // array of profiles
29
-    error: errorSchema.single,
30
-}
31
-
32
-module.exports = {
33
-    method: 'GET',
34
-    path: '/',
35
-    options: {
36
-        ...pluginConfig.docs,
37
-        tags: ['api'],
38
-        auth: false,
39
-        cors: true,
40
-        handler: async function (request, h) {
41
-            const { filterService } = request.server.services()
42
-            let matchPool = request.query.match_pool
43
-            matchPool = filterService.byDistance(
44
-                matchPool,
45
-                request.query.distance,
46
-            )
47
-            matchPool = filterService.byPresence(
48
-                matchPool,
49
-                request.query.presence,
50
-            )
51
-            try {
52
-                return h
53
-                    .response({
54
-                        ok: true,
55
-                        handler: pluginConfig.handlerType,
56
-                        data: matchPool,
57
-                    })
58
-                    .code(200)
59
-            } catch (err) {
60
-                return h
61
-                    .response({
62
-                        ok: false,
63
-                        handler: pluginConfig.handlerType,
64
-                        data: { error: `${err}` },
65
-                    })
66
-                    .code(409)
67
-            }
68
-        },
69
-        validate: {
70
-            ...validators,
71
-            failAction: 'log',
72
-        },
73
-
74
-        response: {
75
-            status: {
76
-                200: apiSchema.single
77
-                    .append({
78
-                        data: responseSchemas.filteredMatchPool,
79
-                    })
80
-                    .label('api_single_res'),
81
-                409: apiSchema.single
82
-                    .append({
83
-                        data: responseSchemas.error,
84
-                    })
85
-                    .label('error_single_res'),
86
-            },
87
-        },
88
-    },
89
-}

+ 0
- 69
backend/lib/routes/health/get.js Dosyayı Görüntüle

@@ -1,69 +0,0 @@
1
-'use strict'
2
-
3
-const apiSchema = require('../../schemas/api')
4
-const errorSchema = require('../../schemas/errors')
5
-const healthSchema = require('../../schemas/health')
6
-
7
-const pluginConfig = {
8
-    handlerType: 'health',
9
-    docs: {
10
-        description: 'Get server stats',
11
-        notes: 'Returns stats on server status'
12
-    }
13
-}
14
-
15
-const validators = {}
16
-
17
-const responseSchemas = {
18
-    health: healthSchema.stats,
19
-    error: errorSchema.single
20
-}
21
-
22
-module.exports = {
23
-    method: 'GET',
24
-    path: '/',
25
-    options:{
26
-        ...pluginConfig.docs,
27
-        tags: ['api'],
28
-        auth: false,
29
-        cors: true,
30
-        handler: async function (request, h) {
31
-            const { healthService } = request.server.services()
32
-            const stats = await healthService.getStats()
33
-            try {
34
-                return h.response(({
35
-                    ok:true,
36
-                    handler: pluginConfig.handlerType,
37
-                    data: stats
38
-                })).code(200)
39
-            } catch (err) {
40
-                return h
41
-                    .response({
42
-                        ok: false,
43
-                        handler: pluginConfig.handlerType,
44
-                        data: {error: `${err}`}
45
-                    })
46
-                    .code(409)
47
-            }
48
-        },
49
-        validate: {
50
-            ...validators,
51
-            failAction: 'log'
52
-        },
53
-
54
-        response: {
55
-            status: {
56
-                200: apiSchema.single
57
-                    .append({
58
-                        data: responseSchemas.health,
59
-                    })
60
-                    .label('api_single_res'),
61
-                409: apiSchema.single
62
-                    .append({
63
-                        data: responseSchemas.error,
64
-                    })
65
-                    .label('error_single_res'),
66
-            },
67
-        },
68
-    },
69
-}

+ 0
- 176
backend/lib/routes/membership/active.js Dosyayı Görüntüle

@@ -1,176 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const errorSchema = require('../../schemas/errors')
6
-const groupingSchema = require('../../schemas/groupings')
7
-const params = require('../../schemas/params')
8
-
9
-const pluginConfig = {
10
-    handlerType: 'grouping',
11
-    docs: {
12
-        description: 'active memberships',
13
-        notes: 'A list of groupings with active membership',
14
-    },
15
-}
16
-
17
-const validators = {
18
-    /** Validate the header (cookie check) */
19
-    // headers: true,
20
-
21
-    /** Validate the route params (/active/{thing}) */
22
-    params: params.profileId,
23
-
24
-    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
25
-    query: Joi.object({ type: Joi.string().lowercase().min(6).max(11) }),
26
-
27
-    /** Validate the incoming payload (POST method) */
28
-    // payload: true,
29
-}
30
-
31
-const responseSchemas = {
32
-    single: groupingSchema.single,
33
-    list: groupingSchema.listWithProfiles,
34
-    error: errorSchema.single,
35
-}
36
-
37
-const _activeGroupingIds = allMemberships => {
38
-    const active = {}
39
-    allMemberships.forEach(membership => {
40
-        if (!membership.is_active) return
41
-        if (!active[membership.grouping_id]) {
42
-            active[membership.grouping_id] = []
43
-        }
44
-        active[membership.grouping_id].push(membership)
45
-    })
46
-    const ids = []
47
-    Object.values(active).forEach(profileListInGrouping => {
48
-        if (profileListInGrouping.length == 2) {
49
-            ids.push(profileListInGrouping[0].grouping_id)
50
-        }
51
-    })
52
-    return ids
53
-}
54
-
55
-module.exports = {
56
-    method: 'GET',
57
-    path: '/{profile_id}',
58
-    options: {
59
-        ...pluginConfig.docs,
60
-        tags: ['api'],
61
-        /** Protect this route with authentication? */
62
-        auth: false,
63
-        cors: true,
64
-        handler: async function (request, h) {
65
-            const { membershipService, profileService, userService } =
66
-                request.server.services()
67
-            const membershipType = request.query.type
68
-
69
-            const profileId = request.params.profile_id
70
-            const groupings = await membershipService.findGroupingsByProfileId(
71
-                profileId,
72
-                membershipType,
73
-            )
74
-            if (!groupings.length) {
75
-                return {
76
-                    ok: true,
77
-                    handler: pluginConfig.handlerType,
78
-                    data: [],
79
-                }
80
-            }
81
-            const groupingIds = groupings.map(grouping => grouping.grouping_id)
82
-            const memberships =
83
-                await membershipService.findMemberships(groupingIds)
84
-            let profileIds = memberships
85
-                .filter(membership => membership.profile_id !== profileId)
86
-                .map(membership => membership.profile_id)
87
-            profileIds =
88
-                !profileIds.length || profileIds[0] === undefined
89
-                    ? []
90
-                    : profileIds
91
-            /** Assemble complete profiles to reference and pass */
92
-            const completedProfiles = !profileIds.length
93
-                ? []
94
-                : await profileService.getProfilesFor(profileIds, 'participant')
95
-            /**
96
-             * Heavily process the result by storing just a profile_id
97
-             * and attach complete profiles
98
-             * !: This still assumes only ONE other profile
99
-             * TODO: should be refactored to many other profiles
100
-             */
101
-            const reformattedGroupings =
102
-                groupings.length && completedProfiles.length
103
-                    ? groupings.map(grouping => {
104
-                          const otherPid = grouping.profiles.find(
105
-                              p => p.profile_id != profileId,
106
-                          ).profile_id
107
-                          grouping.profile = completedProfiles.find(
108
-                              p => otherPid == p.profile_id,
109
-                          )
110
-                          grouping.is_paired = _activeGroupingIds(
111
-                              memberships,
112
-                          ).includes(grouping.grouping_id)
113
-                          delete grouping.profiles
114
-                          return grouping
115
-                      })
116
-                    : []
117
-            /** Grabs revealTags */
118
-            const revealTags =
119
-                profileIds.length && groupingIds.length
120
-                    ? await profileService.getTagsFor(
121
-                          profileIds,
122
-                          groupingIds,
123
-                          'reveal',
124
-                      )
125
-                    : undefined
126
-
127
-            /** If the revealTags exist, the completedProfile's hidden info is
128
-             * removed and replaced with the completedProfile's user information
129
-             * Otherwise the completedProfiles remain unchanged
130
-             */
131
-            const user = completedProfiles.length
132
-                ? await userService.findById(
133
-                      completedProfiles.map(p => p.user_id),
134
-                  )
135
-                : undefined
136
-
137
-            // TODO: Refactor this. Is it safe to always use completedProfiles[0]?
138
-            if (revealTags && user) {
139
-                revealTags.forEach(t => {
140
-                    if (!t.tag.tag_description) return
141
-                    completedProfiles[0][t.tag.tag_description] =
142
-                        user[t.tag.tag_description]
143
-                })
144
-            }
145
-
146
-            try {
147
-                return {
148
-                    ok: true,
149
-                    handler: pluginConfig.handlerType,
150
-                    data: reformattedGroupings,
151
-                }
152
-            } catch (err) {
153
-                return {
154
-                    ok: false,
155
-                    handler: pluginConfig.handlerType,
156
-                    data: { error: `${err}` },
157
-                }
158
-            }
159
-        },
160
-
161
-        /** Validate based on validators object */
162
-        validate: {
163
-            ...validators,
164
-            failAction: 'log',
165
-        },
166
-
167
-        /** Validate the server response */
168
-        response: {
169
-            schema: apiSchema.single
170
-                .append({
171
-                    data: responseSchemas.list,
172
-                })
173
-                .label('grouping_list_res'),
174
-        },
175
-    },
176
-}

+ 0
- 150
backend/lib/routes/membership/join.js Dosyayı Görüntüle

@@ -1,150 +0,0 @@
1
-const Joi = require('joi')
2
-
3
-const apiSchema = require('../../schemas/api')
4
-const errorSchema = require('../../schemas/errors')
5
-const groupingSchema = require('../../schemas/groupings')
6
-const params = require('../../schemas/params')
7
-
8
-const pluginConfig = {
9
-    handlerType: 'grouping',
10
-    docs: {
11
-        description: 'join',
12
-        notes: 'Join a grouping by creating a membership record',
13
-    },
14
-}
15
-
16
-const validators = {
17
-    params: params.profileId,
18
-    payload: groupingSchema.single
19
-        .append({
20
-            target_id: Joi.number().required(),
21
-            role: Joi.string(),
22
-        })
23
-        .label('grouping_membership_single'),
24
-}
25
-
26
-const responseSchemas = {
27
-    response: Joi.object({
28
-        memberships: Joi.array().items(),
29
-        hasMatch: Joi.boolean(),
30
-        groupings: Joi.array().items(),
31
-    }).label('grouping_membership_list'),
32
-    error: errorSchema.single,
33
-}
34
-
35
-module.exports = {
36
-    method: 'POST',
37
-    path: '/{profile_id}/join',
38
-    options: {
39
-        ...pluginConfig.docs,
40
-        tags: ['api'],
41
-        auth: false,
42
-        cors: true,
43
-
44
-        /**
45
-         * Join a grouping by creating a membership record
46
-         * @param {*} request
47
-         * @param {*} h
48
-         * @returns {object}
49
-         */
50
-        handler: async function (request, h) {
51
-            try {
52
-                console.log('---')
53
-                const { membershipService } = request.server.services()
54
-
55
-                /** Grab payload info */
56
-                const profileId = request.params.profile_id
57
-                const res = request.payload
58
-                const groupingToWrite = {
59
-                    grouping_id: res.grouping_id,
60
-                    grouping_name: res.grouping_name,
61
-                    grouping_type: res.grouping_type,
62
-                }
63
-
64
-                /** Default to participant role */
65
-                const role = res.role ? res.role : 'participant'
66
-
67
-                // TODO: LIMIT the amount of groupings by checking type
68
-                // !: You should only be able to match with the target_id ONCE
69
-                // !: You should only be associated with a single company too
70
-
71
-                /** User membership service method to create membership */
72
-                const { memberships, groupings } =
73
-                    await membershipService.joinGrouping(
74
-                        profileId,
75
-                        res.target_id,
76
-                        groupingToWrite,
77
-                        role,
78
-                    )
79
-
80
-                const hasMatch = memberships.every(
81
-                    membership => membership && membership.is_active == true,
82
-                )
83
-
84
-                if (hasMatch) {
85
-                    request.server.methods.notify(
86
-                        `${profileId}.stonk`,
87
-                        {
88
-                            name: `${res.target_id} Match Fffound`,
89
-                            // TODO: add urls for chat
90
-                            url: `<a href="/profile/${res.target_id}">url</a>`,
91
-                            type: 'info',
92
-                        },
93
-                        h,
94
-                    )
95
-                    request.server.methods.notify(
96
-                        `${res.target_id}.stonk`,
97
-                        {
98
-                            name: `${profileId} Match Fffound`,
99
-                            // TODO: add urls for chat
100
-                            url: `<a href="/profile/${profileId}">url</a>`,
101
-                            type: 'info',
102
-                        },
103
-                        h,
104
-                    )
105
-                }
106
-                return h
107
-                    .response({
108
-                        ok: true,
109
-                        handler: pluginConfig.handlerType,
110
-                        data: {
111
-                            memberships,
112
-                            hasMatch,
113
-                            groupings,
114
-                        },
115
-                    })
116
-                    .code(200)
117
-            } catch (err) {
118
-                return h
119
-                    .response({
120
-                        ok: false,
121
-                        handler: pluginConfig.handlerType,
122
-                        data: { error: `${err}` },
123
-                    })
124
-                    .code(409)
125
-            }
126
-        },
127
-
128
-        /** Validate based on validators object */
129
-        validate: {
130
-            ...validators,
131
-            failAction: 'log',
132
-        },
133
-
134
-        /** Validate the server response */
135
-        response: {
136
-            status: {
137
-                200: apiSchema.single
138
-                    .append({
139
-                        data: responseSchemas.response,
140
-                    })
141
-                    .label('join_grouping_res'),
142
-                409: apiSchema.single
143
-                    .append({
144
-                        data: responseSchemas.error,
145
-                    })
146
-                    .label('error_single_res'),
147
-            },
148
-        },
149
-    },
150
-}

+ 0
- 49
backend/lib/routes/membership/leave.js Dosyayı Görüntüle

@@ -1,49 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const pluginConfig = {
6
-    handlerType: 'grouping',
7
-    docs: {
8
-        description: 'leave',
9
-        notes: 'Leave a grouping by editing a membership record',
10
-    },
11
-}
12
-
13
-const validators = {
14
-    leave: {
15
-        payload: Joi.object(),
16
-    },
17
-}
18
-
19
-module.exports = {
20
-    method: 'POST',
21
-    path: '/leave',
22
-    options: {
23
-        ...pluginConfig.docs,
24
-        tags: ['api'],
25
-        auth: false,
26
-        handler: async function (request, h) {
27
-            try {
28
-                return {
29
-                    ok: true,
30
-                    handler: pluginConfig.handlerType,
31
-                    data: { foo: 'bar' },
32
-                }
33
-            } catch (err) {
34
-                return {
35
-                    ok: false,
36
-                    handler: pluginConfig.handlerType,
37
-                    data: { error: `${err}` },
38
-                }
39
-            }
40
-        },
41
-        validate: validators.leave,
42
-        response: {
43
-            schema: apiSchema.single.append({
44
-                data: validators.leave,
45
-            }),
46
-            failAction: 'log',
47
-        },
48
-    },
49
-}

+ 0
- 137
backend/lib/routes/membership/reveal.js Dosyayı Görüntüle

@@ -1,137 +0,0 @@
1
-const Joi = require('joi')
2
-
3
-const apiSchema = require('../../schemas/api')
4
-const errorSchema = require('../../schemas/errors')
5
-
6
-const pluginConfig = {
7
-    handlerType: 'reveal',
8
-    docs: {
9
-        description: 'reveal',
10
-        notes: 'Reveal profile information to a grouping by membership',
11
-    },
12
-}
13
-
14
-const validators = {
15
-    params: Joi.object({ grouping_id: Joi.number() }),
16
-    query: Joi.object({ profile_id: Joi.number(), tag_id: Joi.number() }),
17
-}
18
-
19
-const responseSchemas = {
20
-    response: Joi.object({
21
-        tags: Joi.array().items(),
22
-    }),
23
-    error: errorSchema.single,
24
-}
25
-module.exports = {
26
-    method: 'POST',
27
-    path: '/{grouping_id}/reveal',
28
-    options: {
29
-        ...pluginConfig.docs,
30
-        tags: ['api'],
31
-        auth: false,
32
-        cors: true,
33
-        handler: async function (request, h) {
34
-            const { membershipService, profileService, userService } =
35
-                request.server.services()
36
-            const grouping_id = request.params.grouping_id
37
-            const { profile_id, tag_id } = request.query
38
-            try {
39
-                const associations = await profileService.revealProfileInfo({
40
-                    profile_id,
41
-                    grouping_id,
42
-                    tag_id,
43
-                    is_deleted: false,
44
-                })
45
-
46
-                // Notify both profiles that information has been revealed
47
-                const memberships = await membershipService.findMemberships([
48
-                    grouping_id,
49
-                ])
50
-                const idsInGroup = memberships.map(
51
-                    membership => membership.profile_id,
52
-                )
53
-                if (idsInGroup.length > 2)
54
-                    return console.error(
55
-                        'ERROR: idsInGroup cannot have more than 2 entries: ',
56
-                        idsInGroup,
57
-                    )
58
-                // Grab User Info from Users Table
59
-                const completeProfile = await profileService.getProfilesFor(
60
-                    [profile_id],
61
-                    'participant',
62
-                )
63
-                const userInfo = await userService.findById(
64
-                    completeProfile[0].user_id,
65
-                )
66
-
67
-                // Grab the TagAssociation that matches the revealed profile
68
-                // TODO: Check if there are multiple matching associations(?)(there shouldn't be)
69
-                let matchingAssociation = null
70
-                associations.forEach(tagAssoc => {
71
-                    if (
72
-                        tagAssoc.grouping_id === grouping_id &&
73
-                        tagAssoc.profile_id === profile_id &&
74
-                        tagAssoc.tag_id === tag_id
75
-                    ) {
76
-                        matchingAssociation = tagAssoc
77
-                    }
78
-                })
79
-                const description = matchingAssociation.tag.tag_description
80
-
81
-                idsInGroup.forEach(profile_id => {
82
-                    request.server.methods.notify(
83
-                        `${profile_id}.stonk`,
84
-                        {
85
-                            name: 'REVEALED_INFO',
86
-                            revealed_info: userInfo[description],
87
-                            profile_id: completeProfile[0].profile_id,
88
-                            grouping_id: grouping_id,
89
-                            tag: tag_id,
90
-                            description,
91
-                            type: 'info',
92
-                            url: `<a href="/chat/${profile_id}">url</a>`
93
-                        },
94
-                        h,
95
-                    )
96
-                })
97
-                return h
98
-                    .response({
99
-                        ok: true,
100
-                        handler: pluginConfig.handlerType,
101
-                        data: { tags: associations },
102
-                    })
103
-                    .code(200)
104
-            } catch (err) {
105
-                return h
106
-                    .response({
107
-                        ok: false,
108
-                        handler: pluginConfig.handlerType,
109
-                        data: { error: `${err}` },
110
-                    })
111
-                    .code(409)
112
-            }
113
-        },
114
-
115
-        /** Validate based on validators object */
116
-        validate: {
117
-            ...validators,
118
-            failAction: 'log',
119
-        },
120
-
121
-        /** Validate the server response */
122
-        response: {
123
-            status: {
124
-                200: apiSchema.single
125
-                    .append({
126
-                        data: responseSchemas.response,
127
-                    })
128
-                    .label('reveal_res'),
129
-                409: apiSchema.single
130
-                    .append({
131
-                        data: responseSchemas.error,
132
-                    })
133
-                    .label('error_single_res'),
134
-            },
135
-        },
136
-    },
137
-}

+ 0
- 53
backend/lib/routes/notification/index.js Dosyayı Görüntüle

@@ -1,53 +0,0 @@
1
-const Joi = require('joi')
2
-const apiSchema = require('../../schemas/api')
3
-const errorSchema = require('../../schemas/errors')
4
-const params = require('../../schemas/params')
5
-
6
-const pluginConfig = {
7
-    handlerType: 'notifictaion',
8
-    docs: {
9
-        description: 'subscribe',
10
-        notes: 'Subscribe to notifications based on profile_id',
11
-    },
12
-}
13
-
14
-const validators = {
15
-    params: params.profileId,
16
-}
17
-
18
-module.exports = {
19
-    method: 'GET',
20
-    path: '/{profile_id}/subscribe',
21
-    options: {
22
-        ...pluginConfig.docs,
23
-        tags: ['api'],
24
-        auth: false,
25
-        cors: true,
26
-        handler: async (request, h) => {
27
-            const { profile_id } = request.params
28
-
29
-            /**
30
-             * Write the initial stream
31
-             * !: this must remain open for notifications to work
32
-             */
33
-            return request.server.methods.notify(
34
-                `${profile_id}.stonk`,
35
-                {
36
-                    profile_id,
37
-                    name: 'BDGRS',
38
-                    price: (500 + Math.floor(Math.random() * 100)).toString(),
39
-                    order: Math.floor(Math.random() * 2) === 1 ? 'BUY' : 'SELL',
40
-                    type: 'info',
41
-                },
42
-                h,
43
-                true,
44
-            )
45
-        },
46
-
47
-        /** Validate based on validators object */
48
-        validate: {
49
-            ...validators,
50
-            failAction: 'log',
51
-        },
52
-    },
53
-}

+ 0
- 80
backend/lib/routes/profile/get.js Dosyayı Görüntüle

@@ -1,80 +0,0 @@
1
-'use strict'
2
-
3
-const apiSchema = require('../../schemas/api')
4
-const errorSchema = require('../../schemas/errors')
5
-const profileSchema = require('../../schemas/profiles')
6
-const params = require('../../schemas/params')
7
-
8
-const pluginConfig = {
9
-    handlerType: 'profile',
10
-    docs: {
11
-        description: 'Returns a single profile with tags',
12
-        notes: 'returns from the Profiles Table',
13
-    },
14
-}
15
-
16
-const responseSchemas = {
17
-    profile: profileSchema.single,
18
-    error: errorSchema.single,
19
-}
20
-
21
-const validators = {
22
-    params: params.profileId,
23
-}
24
-
25
-module.exports = {
26
-    method: 'GET',
27
-    path: '/{profile_id}',
28
-    options: {
29
-        ...pluginConfig.docs,
30
-        tags: ['api'],
31
-        // auth: 'default_jwt',
32
-        auth: false,
33
-        cors: true,
34
-        handler: async function (request, h) {
35
-            const { profile_id } = request.params
36
-            const { profileService } = request.server.services()
37
-
38
-            const res = {
39
-                ok: true,
40
-                handler: pluginConfig.handlerType,
41
-                data: null,
42
-            }
43
-
44
-            res.data = await profileService.getProfile(profile_id)
45
-
46
-            try {
47
-                return h.response(res).code(200)
48
-            } catch (err) {
49
-                return h
50
-                    .response({
51
-                        ok: false,
52
-                        handler: pluginConfig.handlerType,
53
-                        data: { error: `${err}` },
54
-                    })
55
-                    .code(409)
56
-            }
57
-        },
58
-        /** Validate based on validators object */
59
-        validate: {
60
-            ...validators,
61
-            failAction: 'log',
62
-        },
63
-
64
-        /** Validate the server response */
65
-        response: {
66
-            status: {
67
-                200: apiSchema.single
68
-                    .append({
69
-                        data: responseSchemas.profile,
70
-                    })
71
-                    .label('profile_single_res'),
72
-                409: apiSchema.single
73
-                    .append({
74
-                        data: responseSchemas.error,
75
-                    })
76
-                    .label('error_single_res'),
77
-            },
78
-        },
79
-    },
80
-}

+ 0
- 85
backend/lib/routes/profile/insert.js Dosyayı Görüntüle

@@ -1,85 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const errorSchema = require('../../schemas/errors')
6
-const surveyResponseSchema = require('../../schemas/responses')
7
-const params = require('../../schemas/params')
8
-
9
-const pluginConfig = {
10
-    handlerType: 'profile',
11
-    docs: {
12
-        description: 'Insert responses',
13
-        notes: 'Insert new responses',
14
-    },
15
-}
16
-
17
-const responseSchemas = {
18
-    response: surveyResponseSchema.single,
19
-    error: errorSchema.single,
20
-}
21
-
22
-module.exports = {
23
-    method: 'POST',
24
-    path: '/{profile_id}/insert/{response_key_id?}',
25
-    options: {
26
-        ...pluginConfig.docs,
27
-        tags: ['api'],
28
-        /** Protect this route with authentication? */
29
-        auth: false,
30
-        cors: true,
31
-
32
-        handler: async function (request, h) {
33
-            const { profileService } = request.services()
34
-            /** Grab payload info */
35
-            const res = request.payload
36
-
37
-            try {
38
-                // TODO: Currently passwords are stored in plain text, big no no...
39
-                const insertedResponse =
40
-                    await profileService.insertSingleResponseForProfile(res)
41
-
42
-                if (!insertedResponse) {
43
-                    throw new Error('Response not inserted')
44
-                }
45
-
46
-                return h
47
-                    .response({
48
-                        ok: true,
49
-                        handler: pluginConfig.handlerType,
50
-                        data: insertedResponse,
51
-                    })
52
-                    .code(200)
53
-            } catch (err) {
54
-                return h
55
-                    .response({
56
-                        ok: false,
57
-                        handler: pluginConfig.handlerType,
58
-                        data: { error: `${err}` },
59
-                    })
60
-                    .code(409)
61
-            }
62
-        },
63
-
64
-        /** Validate based on validators object */
65
-        validate: {
66
-            failAction: 'log',
67
-        },
68
-
69
-        /** Validate the server response */
70
-        response: {
71
-            status: {
72
-                200: apiSchema.single
73
-                    .append({
74
-                        data: responseSchemas.response,
75
-                    })
76
-                    .label('response_list_res'),
77
-                409: apiSchema.single
78
-                    .append({
79
-                        data: responseSchemas.error,
80
-                    })
81
-                    .label('error_single_res'),
82
-            },
83
-        },
84
-    },
85
-}

+ 0
- 81
backend/lib/routes/profile/match.js Dosyayı Görüntüle

@@ -1,81 +0,0 @@
1
-'use strict'
2
-
3
-const apiSchema = require('../../schemas/api')
4
-const errorSchema = require('../../schemas/errors')
5
-const surveyResponseSchema = require('../../schemas/responses')
6
-
7
-const pluginConfig = {
8
-    handlerType: 'match',
9
-    docs: {
10
-        description: 'matches',
11
-        notes: 'Match everyone',
12
-    },
13
-}
14
-
15
-const validators = {}
16
-
17
-const responseSchemas = {
18
-    response: surveyResponseSchema.list,
19
-    error: errorSchema.single,
20
-}
21
-
22
-module.exports = {
23
-    method: 'GET',
24
-    path: '/match',
25
-    options: {
26
-        ...pluginConfig.docs,
27
-        tags: ['api'],
28
-        /** Protect this route with authentication? */
29
-        auth: false,
30
-
31
-        handler: async function (request, h) {
32
-            const { matchService, matchQueueService } =
33
-                request.server.services()
34
-            const allQueues = await matchQueueService.getAllQueues()
35
-            const matched = await matchService.calcMatches(allQueues)
36
-            try {
37
-                if (!allQueues) {
38
-                    throw new RangeError('Unable to match profiles')
39
-                }
40
-
41
-                return h
42
-                    .response({
43
-                        ok: true,
44
-                        handler: pluginConfig.handlerType,
45
-                        data: matched,
46
-                    })
47
-                    .code(200)
48
-            } catch (err) {
49
-                return h
50
-                    .response({
51
-                        ok: false,
52
-                        handler: pluginConfig.handlerType,
53
-                        data: { error: `${err}` },
54
-                    })
55
-                    .code(409)
56
-            }
57
-        },
58
-
59
-        /** Validate based on validators object */
60
-        validate: {
61
-            ...validators,
62
-            failAction: 'log',
63
-        },
64
-
65
-        /** Validate the server response */
66
-        response: {
67
-            status: {
68
-                200: apiSchema.single
69
-                    .append({
70
-                        data: responseSchemas.response,
71
-                    })
72
-                    .label('response_list_res'),
73
-                409: apiSchema.single
74
-                    .append({
75
-                        data: responseSchemas.error,
76
-                    })
77
-                    .label('error_single_res'),
78
-            },
79
-        },
80
-    },
81
-}

+ 0
- 97
backend/lib/routes/profile/patch-queue.js Dosyayı Görüntüle

@@ -1,97 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const errorSchema = require('../../schemas/errors')
6
-const profileSchema = require('../../schemas/profiles')
7
-const params = require('../../schemas/params')
8
-
9
-const pluginConfig = {
10
-    handlerType: 'profile',
11
-    docs: {
12
-        description: 'Updates match queue in place',
13
-        notes: 'Updates in place and does not delete from table',
14
-    },
15
-}
16
-
17
-const responseSchemas = {
18
-    response: Joi.array().items(
19
-        Joi.alternatives().try(
20
-            Joi.number().optional(),
21
-            profileSchema.single.optional(),
22
-        ),
23
-    ),
24
-    error: errorSchema.single,
25
-}
26
-
27
-const validators = {
28
-    params: params.profileId.append({ target_id: Joi.number() }),
29
-    query: params.profileInclude.append({ reinsert: Joi.boolean() }),
30
-}
31
-
32
-module.exports = {
33
-    method: 'PATCH',
34
-    path: '/{profile_id}/queue/{target_id}/delete',
35
-    options: {
36
-        ...pluginConfig.docs,
37
-        tags: ['api'],
38
-        /** Protect this route with authentication? */
39
-        auth: false,
40
-        cors: true,
41
-        handler: async function (request, h) {
42
-            const { profile_id, target_id } = request.params
43
-            const { include_profile, reinsert } = request.query
44
-            const { profileService, matchQueueService } =
45
-                request.server.services()
46
-
47
-            const updatedQueue = await matchQueueService.markAsDeleted(
48
-                profile_id,
49
-                target_id,
50
-                reinsert,
51
-            )
52
-            const queueIds = updatedQueue.map(entry => entry.target_id)
53
-
54
-            const res = {
55
-                ok: true,
56
-                handler: pluginConfig.handlerType,
57
-                data:
58
-                    include_profile == true
59
-                        ? await profileService.getProfilesFor(queueIds)
60
-                        : queueIds,
61
-            }
62
-
63
-            try {
64
-                return h.response(res).code(200)
65
-            } catch (err) {
66
-                return h
67
-                    .response({
68
-                        ok: false,
69
-                        handler: pluginConfig.handlerType,
70
-                        data: { error: `${err}` },
71
-                    })
72
-                    .code(409)
73
-            }
74
-        },
75
-        /** Validate based on validators object */
76
-        validate: {
77
-            ...validators,
78
-            failAction: 'log',
79
-        },
80
-
81
-        /** Validate the server response */
82
-        response: {
83
-            status: {
84
-                200: apiSchema.single
85
-                    .append({
86
-                        data: responseSchemas.response,
87
-                    })
88
-                    .label('match_queue_res'),
89
-                409: apiSchema.single
90
-                    .append({
91
-                        data: responseSchemas.error,
92
-                    })
93
-                    .label('error_single_res'),
94
-            },
95
-        },
96
-    },
97
-}

+ 0
- 107
backend/lib/routes/profile/queue.js Dosyayı Görüntüle

@@ -1,107 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const errorSchema = require('../../schemas/errors')
6
-const profileSchema = require('../../schemas/profiles')
7
-
8
-const pluginConfig = {
9
-    handlerType: 'profile',
10
-    docs: {
11
-        description: 'Returns previously scored profiles',
12
-        notes: 'returns from the MatchQueue Table',
13
-    },
14
-}
15
-
16
-const responseSchemas = {
17
-    response: Joi.array().items(
18
-        Joi.alternatives().try(Joi.number(), profileSchema.single),
19
-    ),
20
-    error: errorSchema.single,
21
-}
22
-
23
-const validators = {
24
-    params: Joi.object({
25
-        profile_id: Joi.string(),
26
-    }),
27
-    query: Joi.object({
28
-        include_profile: Joi.bool(),
29
-        limit: Joi.number(),
30
-        offset: Joi.number(),
31
-    }),
32
-}
33
-
34
-module.exports = {
35
-    method: 'GET',
36
-    path: '/{profile_id}/queue',
37
-    options: {
38
-        ...pluginConfig.docs,
39
-        tags: ['api'],
40
-        /** Protect this route with authentication? */
41
-        auth: false,
42
-        cors: true,
43
-        handler: async function (request, h) {
44
-            const { profile_id } = request.params
45
-            const { limit, offset } = request.query
46
-            const { profileService, matchQueueService } =
47
-                request.server.services()
48
-
49
-            const queue = await matchQueueService.getQueue(
50
-                profile_id,
51
-                limit,
52
-                offset,
53
-            )
54
-            const queueIds = queue.map(entry => entry.target_id)
55
-
56
-            // HELP: I think there's an issue here
57
-            // queueIds spits out the queue profiles in the correct order
58
-            // ~However~ when it goes through getProfilesFor
59
-            // it comes back in literal database order regardless of is_deleted status
60
-            // console.log(
61
-            //     'include_profile results',
62
-            //     await profileService.getProfilesFor(queueIds),
63
-            // )
64
-            try {
65
-                return h
66
-                    .response({
67
-                        ok: true,
68
-                        handler: pluginConfig.handlerType,
69
-                        data: await profileService.getProfilesFor(
70
-                            queueIds,
71
-                            'participant',
72
-                        ),
73
-                    })
74
-                    .code(200)
75
-            } catch (err) {
76
-                return h
77
-                    .response({
78
-                        ok: false,
79
-                        handler: pluginConfig.handlerType,
80
-                        data: { error: `${err}` },
81
-                    })
82
-                    .code(409)
83
-            }
84
-        },
85
-        /** Validate based on validators object */
86
-        validate: {
87
-            ...validators,
88
-            failAction: 'log',
89
-        },
90
-
91
-        /** Validate the server response */
92
-        response: {
93
-            status: {
94
-                200: apiSchema.single
95
-                    .append({
96
-                        data: responseSchemas.response,
97
-                    })
98
-                    .label('match_queue_res'),
99
-                409: apiSchema.single
100
-                    .append({
101
-                        data: responseSchemas.error,
102
-                    })
103
-                    .label('error_single_res'),
104
-            },
105
-        },
106
-    },
107
-}

+ 0
- 107
backend/lib/routes/profile/respond.js Dosyayı Görüntüle

@@ -1,107 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const errorSchema = require('../../schemas/errors')
6
-const surveyResponseSchema = require('../../schemas/responses')
7
-const params = require('../../schemas/params')
8
-
9
-const pluginConfig = {
10
-    handlerType: 'profile',
11
-    docs: {
12
-        description: 'Update profile',
13
-        notes: 'Update profile responses',
14
-    },
15
-}
16
-
17
-const responseSchemas = {
18
-    response: surveyResponseSchema.list,
19
-    error: errorSchema.single,
20
-}
21
-
22
-const validators = {
23
-    /** Validate the header (cookie check) */
24
-    // headers: true,
25
-
26
-    /** Validate the route params (/active/{thing}) */
27
-    params: params.profileId,
28
-
29
-    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
30
-    query: Joi.object({
31
-        response_key_id: Joi.number(),
32
-        val: Joi.string(),
33
-    }),
34
-    /** Validate the incoming payload (POST method) */
35
-    // payload: responseSchemas.responses,
36
-}
37
-
38
-module.exports = {
39
-    method: 'POST',
40
-    path: '/{profile_id}/respond',
41
-    options: {
42
-        ...pluginConfig.docs,
43
-        tags: ['api'],
44
-        /** Protect this route with authentication? */
45
-        auth: false,
46
-        cors: true,
47
-        handler: async function (request, h) {
48
-            const { profileService } = request.services()
49
-
50
-            const profileId = request.params.profile_id
51
-            const responseToSave = {
52
-                profile_id: profileId,
53
-                response_key_id: request.query.response_key_id,
54
-                val: request.query.val,
55
-            }
56
-            const allResponses = await profileService.saveResponseForProfile(
57
-                profileId,
58
-                responseToSave,
59
-            )
60
-
61
-            try {
62
-                // profileService.saveResponseForProfile() will return null if it exists
63
-                if (!allResponses) {
64
-                    throw new RangeError('Response already exists')
65
-                }
66
-
67
-                return h
68
-                    .response({
69
-                        ok: true,
70
-                        handler: pluginConfig.handlerType,
71
-                        data: allResponses,
72
-                    })
73
-                    .code(201)
74
-            } catch (err) {
75
-                return h
76
-                    .response({
77
-                        ok: false,
78
-                        handler: pluginConfig.handlerType,
79
-                        data: { error: `${err}` },
80
-                    })
81
-                    .code(409)
82
-            }
83
-        },
84
-
85
-        /** Validate based on validators object */
86
-        validate: {
87
-            ...validators,
88
-            failAction: 'log',
89
-        },
90
-
91
-        /** Validate the server response */
92
-        response: {
93
-            status: {
94
-                201: apiSchema.single
95
-                    .append({
96
-                        data: responseSchemas.response,
97
-                    })
98
-                    .label('response_list_res'),
99
-                409: apiSchema.single
100
-                    .append({
101
-                        data: responseSchemas.error,
102
-                    })
103
-                    .label('error_single_res'),
104
-            },
105
-        },
106
-    },
107
-}

+ 0
- 118
backend/lib/routes/profile/score.js Dosyayı Görüntüle

@@ -1,118 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const errorSchema = require('../../schemas/errors')
6
-const params = require('../../schemas/params')
7
-const profileSchema = require('../../schemas/profiles')
8
-
9
-const pluginConfig = {
10
-    handlerType: 'score',
11
-    docs: {
12
-        description: 'scores',
13
-        notes: 'A list of profile scores',
14
-    },
15
-}
16
-
17
-const validators = {
18
-    /** Validate the header (cookie check) */
19
-    // headers: true,
20
-
21
-    /** Validate the route params (/active/{thing}) */
22
-    params: params.profileId,
23
-
24
-    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
25
-    query: Joi.object({
26
-        max_distance: Joi.number(),
27
-        unit: Joi.string(),
28
-    }),
29
-    /** Validate the incoming payload (POST method) */
30
-    // payload: true,
31
-}
32
-
33
-const responseSchemas = {
34
-    response: Joi.array().items(Joi.object()),
35
-    error: errorSchema.single,
36
-}
37
-
38
-module.exports = {
39
-    method: 'GET',
40
-    path: '/{profile_id}/score',
41
-    options: {
42
-        ...pluginConfig.docs,
43
-        tags: ['api'],
44
-        /** Protect this route with authentication? */
45
-        auth: false,
46
-        cors: true,
47
-        handler: async function (request, h) {
48
-            const { profileService, matchQueueService } =
49
-                request.server.services()
50
-
51
-            const profileId = request.params.profile_id
52
-            const maxDistanceMiles = request.query.max_distance
53
-            const distanceUnit = request.query.unit
54
-                ? request.query.unit
55
-                : 'mile'
56
-            const duration = request.query.duration
57
-            const presence =
58
-                request.query.presence === 'in_person'
59
-                    ? 'onsite'
60
-                    : request.query.presence
61
-            const certifications = request.query.certifications
62
-            const scoredProfiles = await profileService.scoreProfilesFor(
63
-                profileId,
64
-                maxDistanceMiles,
65
-                distanceUnit,
66
-                duration,
67
-                presence,
68
-                certifications,
69
-            )
70
-            try {
71
-                if (!scoredProfiles) {
72
-                    throw new RangeError('Unable to score profiles')
73
-                }
74
-                await matchQueueService.saveMatchQueue(
75
-                    profileId,
76
-                    scoredProfiles.map(profile => profile.profile_id),
77
-                )
78
-                return h
79
-                    .response({
80
-                        ok: true,
81
-                        handler: pluginConfig.handlerType,
82
-                        data: scoredProfiles,
83
-                    })
84
-                    .code(200)
85
-            } catch (err) {
86
-                return h
87
-                    .response({
88
-                        ok: false,
89
-                        handler: pluginConfig.handlerType,
90
-                        data: { error: `${err}` },
91
-                    })
92
-                    .code(409)
93
-            }
94
-        },
95
-
96
-        /** Validate based on validators object */
97
-        validate: {
98
-            ...validators,
99
-            failAction: 'log',
100
-        },
101
-
102
-        /** Validate the server response */
103
-        response: {
104
-            status: {
105
-                200: apiSchema.single
106
-                    .append({
107
-                        data: responseSchemas.response,
108
-                    })
109
-                    .label('profile_list_res'),
110
-                409: apiSchema.single
111
-                    .append({
112
-                        data: responseSchemas.error,
113
-                    })
114
-                    .label('error_single_res'),
115
-            },
116
-        },
117
-    },
118
-}

+ 0
- 102
backend/lib/routes/profile/update.js Dosyayı Görüntüle

@@ -1,102 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const errorSchema = require('../../schemas/errors')
6
-const surveyResponseSchema = require('../../schemas/responses')
7
-const params = require('../../schemas/params')
8
-
9
-const pluginConfig = {
10
-    handlerType: 'profile',
11
-    docs: {
12
-        description: 'Update profile',
13
-        notes: 'Update profile responses',
14
-    },
15
-}
16
-
17
-const responseSchemas = {
18
-    response: surveyResponseSchema.list,
19
-    error: errorSchema.single,
20
-}
21
-
22
-const validators = {
23
-    /** Validate the header (cookie check) */
24
-    // headers: true,
25
-
26
-    /** Validate the route params (/active/{thing}) */
27
-    params: params.profileId,
28
-
29
-    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
30
-    // query: true,
31
-    /** Validate the incoming payload (POST method) */
32
-    payload: responseSchemas.responses,
33
-}
34
-
35
-module.exports = {
36
-    method: 'PATCH',
37
-    path: '/{profile_id}/update/{response_id?}',
38
-    options: {
39
-        ...pluginConfig.docs,
40
-        tags: ['api'],
41
-        /** Protect this route with authentication? */
42
-        auth: false,
43
-
44
-        handler: async function (request, h) {
45
-            const { profileService } = request.services()
46
-            const profileId = request.params.profile_id
47
-
48
-            /** Grab payload info */
49
-            const res = request.payload
50
-
51
-            try {
52
-                const updatedResponses =
53
-                    await profileService.updateResponsesInProfile(
54
-                        profileId,
55
-                        res,
56
-                    )
57
-
58
-                if (!updatedResponses) {
59
-                    throw new RangeError('Response not updated')
60
-                }
61
-
62
-                return h
63
-                    .response({
64
-                        ok: true,
65
-                        handler: pluginConfig.handlerType,
66
-                        data: updatedResponses,
67
-                    })
68
-                    .code(200)
69
-            } catch (err) {
70
-                return h
71
-                    .response({
72
-                        ok: false,
73
-                        handler: pluginConfig.handlerType,
74
-                        data: { error: `${err}` },
75
-                    })
76
-                    .code(409)
77
-            }
78
-        },
79
-
80
-        /** Validate based on validators object */
81
-        validate: {
82
-            ...validators,
83
-            failAction: 'log',
84
-        },
85
-
86
-        /** Validate the server response */
87
-        response: {
88
-            status: {
89
-                200: apiSchema.single
90
-                    .append({
91
-                        data: responseSchemas.response,
92
-                    })
93
-                    .label('response_list_res'),
94
-                409: apiSchema.single
95
-                    .append({
96
-                        data: responseSchemas.error,
97
-                    })
98
-                    .label('error_single_res'),
99
-            },
100
-        },
101
-    },
102
-}

+ 0
- 70
backend/lib/routes/survey/questions.js Dosyayı Görüntüle

@@ -1,70 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const surveyResponseSchema = require('../../schemas/responses')
6
-
7
-const pluginConfig = {
8
-    handlerType: 'survey',
9
-    docs: {
10
-        description: 'Get survey questions',
11
-        notes: 'Returns a list of all possible survey questions in the form of response_keys',
12
-    },
13
-}
14
-
15
-/** Validator functions by request method */
16
-const validators = {
17
-    /** Validate the header (cookie check) */
18
-    // headers: true,
19
-    /** Validate the route params (/active/{thing}) */
20
-    // params: true,
21
-    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
22
-    // query: true,
23
-    /** Validate the incoming payload (POST method) */
24
-    // payload: true,
25
-}
26
-const responseSchemas = {
27
-    response: surveyResponseSchema.keys,
28
-}
29
-
30
-module.exports = {
31
-    method: 'GET',
32
-    path: '/questions',
33
-    options: {
34
-        ...pluginConfig.docs,
35
-        tags: ['api'],
36
-        /** Protect this route with authentication? */
37
-        auth: false,
38
-        cors: true,
39
-        handler: async function (request, h) {
40
-            const { responseService } = request.services()
41
-            const responseKeys = await responseService.getResponseKeys()
42
-            try {
43
-                return {
44
-                    ok: true,
45
-                    handler: pluginConfig.handlerType,
46
-                    data: responseKeys,
47
-                }
48
-            } catch (err) {
49
-                return {
50
-                    ok: false,
51
-                    handler: pluginConfig.handlerType,
52
-                    data: { error: err },
53
-                }
54
-            }
55
-        },
56
-
57
-        /** Validate based on validators object */
58
-        validate: { ...validators, failAction: 'log' },
59
-
60
-        /** Validate the server response */
61
-        response: {
62
-            schema: apiSchema.single
63
-                .append({
64
-                    data: responseSchemas.response,
65
-                })
66
-                .label('question_list_res'),
67
-            failAction: 'log',
68
-        },
69
-    },
70
-}

+ 0
- 71
backend/lib/routes/survey/responses.js Dosyayı Görüntüle

@@ -1,71 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const apiSchema = require('../../schemas/api')
5
-const surveyResponseSchema = require('../../schemas/responses')
6
-const params = require('../../schemas/params')
7
-
8
-const pluginConfig = {
9
-    handlerType: 'survey',
10
-    docs: {
11
-        description: 'Get responses to questions',
12
-        notes: 'Returns a list of all survey responses for a user',
13
-    },
14
-}
15
-
16
-/** Validator functions by request method */
17
-const validators = {
18
-    /** Validate the header (cookie check) */
19
-    // headers: true,
20
-    /** Validate the route params (/active/{thing}) */
21
-    params: params.userId,
22
-    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
23
-    // query: true,
24
-    /** Validate the incoming payload (POST method) */
25
-    // payload: true,
26
-}
27
-const responseSchemas = {
28
-    response: surveyResponseSchema.keys,
29
-}
30
-
31
-module.exports = {
32
-    method: 'GET',
33
-    path: '/questions',
34
-    options: {
35
-        ...pluginConfig.docs,
36
-        tags: ['api'],
37
-        /** Protect this route with authentication? */
38
-        auth: false,
39
-
40
-        handler: async function (request, h) {
41
-            const { responseService } = request.services()
42
-            const responseKeys = await responseService.getResponseKeys()
43
-            try {
44
-                return {
45
-                    ok: true,
46
-                    handler: pluginConfig.handlerType,
47
-                    data: responseKeys,
48
-                }
49
-            } catch (err) {
50
-                return {
51
-                    ok: false,
52
-                    handler: pluginConfig.handlerType,
53
-                    data: { error: err },
54
-                }
55
-            }
56
-        },
57
-
58
-        /** Validate based on validators object */
59
-        validate: { ...validators, failAction: 'log' },
60
-
61
-        /** Validate the server response */
62
-        response: {
63
-            schema: apiSchema.single
64
-                .append({
65
-                    data: responseSchemas.response,
66
-                })
67
-                .label('response_list_res'),
68
-            failAction: 'log',
69
-        },
70
-    },
71
-}

+ 0
- 86
backend/lib/routes/tag/get.js Dosyayı Görüntüle

@@ -1,86 +0,0 @@
1
-'use strict'
2
-
3
-const apiSchema = require('../../schemas/api')
4
-const errorSchema = require('../../schemas/errors')
5
-const Joi = require('joi')
6
-
7
-const pluginConfig = {
8
-    handlerType: 'get',
9
-    docs: {
10
-        description: 'Get tags based on membership id',
11
-        notes: 'returns from the Tag Associations Table',
12
-    },
13
-}
14
-
15
-const responseSchemas = {
16
-    tags: Joi.array().items(Joi.object()),
17
-    error: errorSchema.single,
18
-}
19
-
20
-const validators = {
21
-    params: Joi.object({
22
-        profile_id: Joi.string(),
23
-        grouping_id: Joi.string(),
24
-    }),
25
-    query: Joi.object({ category: Joi.string() }),
26
-}
27
-
28
-module.exports = {
29
-    method: 'GET',
30
-    path: '/{profile_id}/tags/{grouping_id}',
31
-    options: {
32
-        ...pluginConfig.docs,
33
-        tags: ['api'],
34
-        /** Protect this route with authentication? */
35
-        auth: false,
36
-        cors: true,
37
-        handler: async function (request, h) {
38
-            const { grouping_id, profile_id } = request.params
39
-            const { profileService } = request.server.services()
40
-            const { category } = request.query
41
-            const revealedTags = await profileService.getTagsFor(
42
-                profile_id,
43
-                grouping_id,
44
-                category,
45
-            )
46
-            try {
47
-                return h
48
-                    .response({
49
-                        ok: true,
50
-                        handler: pluginConfig.handlerType,
51
-                        data: revealedTags,
52
-                    })
53
-                    .code(200)
54
-            } catch (err) {
55
-                return h
56
-                    .response({
57
-                        ok: false,
58
-                        handler: pluginConfig.handlerType,
59
-                        data: { error: `${err}` },
60
-                    })
61
-                    .code(409)
62
-            }
63
-        },
64
-        /** Validate based on validators object */
65
-        validate: {
66
-            ...validators,
67
-            failAction: 'log',
68
-        },
69
-
70
-        /** Validate the server response */
71
-        response: {
72
-            status: {
73
-                200: apiSchema.single
74
-                    .append({
75
-                        data: responseSchemas.tags,
76
-                    })
77
-                    .label('tags_res'),
78
-                409: apiSchema.single
79
-                    .append({
80
-                        data: responseSchemas.error,
81
-                    })
82
-                    .label('error_single_res'),
83
-            },
84
-        },
85
-    },
86
-}

+ 0
- 91
backend/lib/routes/tag/reveal.js Dosyayı Görüntüle

@@ -1,91 +0,0 @@
1
-'use strict'
2
-
3
-const apiSchema = require('../../schemas/api')
4
-const errorSchema = require('../../schemas/errors')
5
-const params = require('../../schemas/params')
6
-const Joi = require('joi')
7
-
8
-const pluginConfig = {
9
-    handlerType: 'reveal',
10
-    docs: {
11
-        description: 'Reveals part of a profile based on tag',
12
-        notes: 'returns from the Tag Associations Table',
13
-    },
14
-}
15
-
16
-const responseSchemas = {
17
-    tags: Joi.array().items(Joi.object()),
18
-    error: errorSchema.single,
19
-}
20
-
21
-const validators = {
22
-    params: params.profileId.append({ tag_id: Joi.number() }),
23
-    payload: Joi.object({
24
-        profile_id: Joi.number(),
25
-        membership_id: Joi.string().optional(),
26
-    }),
27
-}
28
-
29
-module.exports = {
30
-    method: 'POST',
31
-    path: '/{profile_id}/reveal/{tag_id}',
32
-    options: {
33
-        ...pluginConfig.docs,
34
-        tags: ['api'],
35
-        /** Protect this route with authentication? */
36
-        auth: false,
37
-        cors: true,
38
-        handler: async function (request, h) {
39
-            const { profile_id, tag_id } = request.params
40
-            const { profileService } = request.server.services()
41
-
42
-            const revealedTags = await profileService.revealProfileInfo({
43
-                profile_id,
44
-                tag_id,
45
-                is_deleted: false,
46
-            })
47
-            try {
48
-                const tag = profileService.tagLookup[tag_id]
49
-                if (!tag || tag.tag_category != 'reveal') {
50
-                    throw `cannot reveal ${tag} tag`
51
-                }
52
-                return h
53
-                    .response({
54
-                        ok: true,
55
-                        handler: pluginConfig.handlerType,
56
-                        data: revealedTags,
57
-                    })
58
-                    .code(200)
59
-            } catch (err) {
60
-                return h
61
-                    .response({
62
-                        ok: false,
63
-                        handler: pluginConfig.handlerType,
64
-                        data: { error: `${err}` },
65
-                    })
66
-                    .code(409)
67
-            }
68
-        },
69
-        /** Validate based on validators object */
70
-        validate: {
71
-            ...validators,
72
-            failAction: 'log',
73
-        },
74
-
75
-        /** Validate the server response */
76
-        response: {
77
-            status: {
78
-                200: apiSchema.single
79
-                    .append({
80
-                        data: responseSchemas.tags,
81
-                    })
82
-                    .label('reveal_res'),
83
-                409: apiSchema.single
84
-                    .append({
85
-                        data: responseSchemas.error,
86
-                    })
87
-                    .label('error_single_res'),
88
-            },
89
-        },
90
-    },
91
-}

+ 0
- 119
backend/lib/routes/user/create-profile.js Dosyayı Görüntüle

@@ -1,119 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const errorSchema = require('../../schemas/errors')
5
-const params = require('../../schemas/params')
6
-
7
-const pluginConfig = {
8
-    handlerType: 'user',
9
-    docs: {
10
-        description: 'Create profile for user',
11
-        notes: 'Create a profile associated with this user',
12
-    },
13
-}
14
-
15
-const validators = {
16
-    /** Validate the header (cookie check) */
17
-    // headers: true,
18
-
19
-    /** Validate the route params (/active/{thing}) */
20
-    params: params.userId,
21
-
22
-    /** Validate the route query (/active/{thing}?limit=10&offset=10) */
23
-    // query: true,
24
-    /** Validate the incoming payload (POST method) */
25
-    payload: Joi.array().items(
26
-        Joi.object({
27
-            response_key_id: Joi.number().required(),
28
-            val: Joi.string().required(),
29
-        }),
30
-    ),
31
-}
32
-
33
-const responseSchemas = {
34
-    response: Joi.object({
35
-        profile_id: Joi.number(),
36
-        user_id: Joi.number(),
37
-        user_name: Joi.string(),
38
-    }).label('created_profile'),
39
-    error: errorSchema.single,
40
-}
41
-
42
-module.exports = {
43
-    method: 'POST',
44
-    path: '/{user_id}/profile',
45
-    options: {
46
-        ...pluginConfig.docs,
47
-        tags: ['api'],
48
-        /** Protect this route with authentication? */
49
-        auth: false,
50
-        cors: true,
51
-        handler: async function (request, h) {
52
-            const { userService, profileService } = request.server.services()
53
-            const userId = request.params.user_id
54
-            const user = await userService.findById(userId)
55
-            const type = user.is_poster == 1 ? 'poster' : 'seeker'
56
-
57
-            const profiles = await profileService.getCompleteProfilesFor(
58
-                userId,
59
-                type,
60
-            )
61
-
62
-            try {
63
-                if (type === 'seeker' && profiles.length > 0) {
64
-                    throw new RangeError(
65
-                        'Job seekers may only have ONE profile',
66
-                    )
67
-                }
68
-                /** Grab payload info */
69
-                const res = request.payload
70
-                /** Don't log password in response table */
71
-                const resWithoutPass = res.filter(r => {
72
-                    return r.response_key_id !== 9
73
-                })
74
-                const profile =
75
-                    await profileService.saveResponsesCreateProfileFor(
76
-                        userId,
77
-                        resWithoutPass,
78
-                    )
79
-                return h
80
-                    .response({
81
-                        ok: true,
82
-                        handler: pluginConfig.handlerType,
83
-                        data: profile,
84
-                    })
85
-                    .code(201)
86
-            } catch (err) {
87
-                return h
88
-                    .response({
89
-                        ok: false,
90
-                        handler: pluginConfig.handlerType,
91
-                        data: { error: `${err}` },
92
-                    })
93
-                    .code(409)
94
-            }
95
-        },
96
-
97
-        /** Validate based on validators object */
98
-        validate: {
99
-            ...validators,
100
-            failAction: 'log',
101
-        },
102
-
103
-        /** Validate the server response */
104
-        response: {
105
-            status: {
106
-                201: Joi.object({
107
-                    ok: Joi.bool(),
108
-                    handler: Joi.string(),
109
-                    data: responseSchemas.response,
110
-                }).label('created_profile_res'),
111
-                409: Joi.object({
112
-                    ok: Joi.bool(),
113
-                    handler: Joi.string(),
114
-                    data: responseSchemas.error,
115
-                }).label('error_single_res'),
116
-            },
117
-        },
118
-    },
119
-}

+ 0
- 69
backend/lib/routes/user/get-session.js Dosyayı Görüntüle

@@ -1,69 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const pluginConfig = {
6
-    handlerType: 'authentication',
7
-    docs: {
8
-        get: {
9
-            description: 'creates session token for authentication',
10
-            notes: 'Creates session token for authentication',
11
-        },
12
-    },
13
-}
14
-
15
-const validators = {
16
-    payload: Joi.object({
17
-        payload: Joi.object({
18
-            email: Joi.string(),
19
-            name: Joi.string(),
20
-            seeking: Joi.string(),
21
-        }),
22
-    }),
23
-}
24
-
25
-module.exports = {
26
-    method: 'POST',
27
-    path: '/token',
28
-    options: {
29
-        ...pluginConfig.docs.get,
30
-        tags: ['api'],
31
-        auth: false,
32
-        cors: {
33
-            headers: ['Authorization', 'Content-Type'],
34
-            exposedHeaders: ['Authorization', 'Access-Control-Expose-Headers'],
35
-        },
36
-        handler: async function (request, h) {
37
-            const { userService } = request.server.services()
38
-            const res = request.payload
39
-            // NOTE: Session Token set for 5 minutes expiration (default)
40
-            const sessionToken = await userService.createToken(res, 600)
41
-            try {
42
-                const response = h.response({
43
-                    ok: true,
44
-                    handler: pluginConfig.handlerType,
45
-                    data: sessionToken,
46
-                })
47
-                response.header('Authorization', sessionToken)
48
-                return response
49
-            } catch (err) {
50
-                return {
51
-                    ok: false,
52
-                    handler: pluginConfig.handlerType,
53
-                    data: {
54
-                        error: err,
55
-                    },
56
-                }
57
-            }
58
-        },
59
-        validate: {
60
-            ...validators,
61
-            failAction: 'log',
62
-        },
63
-        response: {
64
-            // TODO: change back to accommodate new h.response return values
65
-            schema: Joi.any().label('get_session_res'),
66
-            failAction: 'log',
67
-        },
68
-    },
69
-}

backend/lib/routes/user/authentication.js → backend/lib/routes/user/get-user.js Dosyayı Görüntüle

@@ -1,44 +1,37 @@
1
-'use strict'
2
-
3 1
 const Joi = require('joi')
4
-const params = require('../../schemas/params')
5 2
 
6 3
 const pluginConfig = {
7
-    handlerType: 'password',
4
+    handlerType: 'user',
8 5
     docs: {
9 6
         get: {
10
-            description: 'get password',
11
-            notes: 'Returns a password by the user email passed in the path',
7
+            description: 'get user',
8
+            notes: 'Returns a user by the email passed in the path',
12 9
         },
13 10
     },
14 11
 }
15 12
 
16
-/** Validator functions by request method */
17 13
 const validators = {
18
-    /** Validate the route params (/active/{thing}) */
19
-    params: params.userEmail,
14
+    params: Joi.object({ user_email: Joi.string() }),
20 15
 }
21 16
 
22 17
 module.exports = {
23 18
     method: 'GET',
24
-    path: '/{user_email}/password',
19
+    path: '/{user_email}',
25 20
     options: {
26 21
         ...pluginConfig.docs.get,
27 22
         tags: ['api'],
28 23
         // auth: 'default_jwt',
29 24
         auth: false,
30 25
         cors: true,
31
-        handler: async function (request, h) {
26
+        handler: async (request, h) => {
32 27
             try {
33 28
                 const { userService } = request.services()
34
-                const userEmail = request.params.user_email
35
-
36
-                const password = await userService.getPassword(userEmail)
37
-
29
+                const email = request.params.user_email
30
+                const user = await userService.findByEmail(email)
38 31
                 return {
39 32
                     ok: true,
40 33
                     handler: pluginConfig.handlerType,
41
-                    data: { password: password },
34
+                    data: { user },
42 35
                 }
43 36
             } catch (err) {
44 37
                 return {

+ 0
- 101
backend/lib/routes/user/login.js Dosyayı Görüntüle

@@ -1,101 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const errorSchema = require('../../schemas/errors')
5
-const userSchema = require('../../schemas/user')
6
-
7
-const pluginConfig = {
8
-    handlerType: 'user',
9
-    docs: {
10
-        description: 'login',
11
-        notes: 'Attempt login',
12
-    },
13
-}
14
-
15
-/** Validator functions by request method */
16
-const validators = {
17
-    post: {
18
-        payload: Joi.object({
19
-            user_email: Joi.string(),
20
-            password: Joi.string(),
21
-        }),
22
-    },
23
-    user: userSchema.single,
24
-    error: errorSchema.single,
25
-}
26
-
27
-module.exports = {
28
-    method: 'POST',
29
-    path: '/login',
30
-    options: {
31
-        ...pluginConfig.docs,
32
-        tags: ['api'],
33
-        auth: false,
34
-        cors: true,
35
-        handler: async function (request, h) {
36
-            try {
37
-                const { userService } = request.server.services()
38
-                const res = request.payload
39
-
40
-                // Callback to use as transaction
41
-                const login = async txn => {
42
-                    return await userService.login(
43
-                        {
44
-                            email: res.user_email,
45
-                            password: res.password,
46
-                        },
47
-                        txn,
48
-                    )
49
-                }
50
-
51
-                // Bound context from your plugin server declaration
52
-                await h.context.transaction(login)
53
-
54
-                // Uses Same Logic Behind Initial Sign Up,
55
-                // passing expected credentials to be used for logging in
56
-                const { userCredentials, token } =
57
-                    await userService.makeUserCredentials(res.user_email)
58
-
59
-                return {
60
-                    ok: true,
61
-                    handler: pluginConfig.handlerType,
62
-                    data: {
63
-                        user_email: userCredentials.email,
64
-                        jwt: token,
65
-                        answered: userCredentials,
66
-                    },
67
-                }
68
-            } catch (err) {
69
-                console.error(err)
70
-                return {
71
-                    ok: false,
72
-                    handler: pluginConfig.handlerType,
73
-                    data: { error: `${err}` },
74
-                }
75
-            }
76
-        },
77
-        validate: validators.post,
78
-        response: {
79
-            status: {
80
-                201: Joi.object({
81
-                    ok: Joi.bool(),
82
-                    handler: Joi.string(),
83
-                    data: Joi.object({
84
-                        user_email: Joi.string(),
85
-                        jwt: Joi.string(),
86
-                        answered: Joi.object({
87
-                            email: Joi.string(),
88
-                            name: Joi.string(),
89
-                            seeking: Joi.string(),
90
-                        }),
91
-                    }),
92
-                }).label('login_res'),
93
-                409: Joi.object({
94
-                    ok: Joi.bool(),
95
-                    handler: Joi.string(),
96
-                    data: validators.error,
97
-                }).label('login_error'),
98
-            },
99
-        },
100
-    },
101
-}

+ 0
- 59
backend/lib/routes/user/remove-session.js Dosyayı Görüntüle

@@ -1,59 +0,0 @@
1
-'use strict'
2
-
3
-const { plugin } = require('@hapi/inert')
4
-const Joi = require('joi')
5
-
6
-const pluginConfig = {
7
-    handlerType: 'jwt',
8
-    docs: {
9
-        get: {
10
-            description: 'removes sessionToken from activeSessions upon logout',
11
-            notes: 'On logout, activeSessions no longer holds onto user credentials',
12
-        },
13
-    },
14
-}
15
-
16
-module.exports = {
17
-    method: 'POST',
18
-    path: '/remove-session',
19
-    options: {
20
-        ...pluginConfig.docs.get,
21
-        tags: ['api'],
22
-        auth: false,
23
-        cors: {
24
-            headers: ['Authorization', 'Content-Type'],
25
-            exposedHeaders: ['Authorization', 'Access-Control-Expose-Headers'],
26
-        },
27
-        handler: async function (request, h) {
28
-            const hashedSessionToken = request.payload
29
-            const { userService } = request.server.services()
30
-            try {
31
-                await userService.removeSession(hashedSessionToken)
32
-                return {
33
-                    ok: true,
34
-                    handler: pluginConfig.handlerType,
35
-                    data: {
36
-                        sessionTokenIsRemoved: true,
37
-                    },
38
-                }
39
-            } catch (err) {
40
-                return {
41
-                    ok: false,
42
-                    handler: pluginConfig.handlerType,
43
-                    data: { error: err.message },
44
-                }
45
-            }
46
-        },
47
-        validate: {
48
-            failAction: 'log',
49
-        },
50
-        response: {
51
-            schema: Joi.object({
52
-                ok: Joi.bool(),
53
-                handler: Joi.string(),
54
-                data: Joi.object(),
55
-            }).label('validate_session_res'),
56
-            failAction: 'log',
57
-        },
58
-    },
59
-}

+ 0
- 82
backend/lib/routes/user/send-email.js Dosyayı Görüntüle

@@ -1,82 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const pluginConfig = {
6
-    handlerType: 'email',
7
-    docs: {
8
-        get: {
9
-            description: 'sends confirmation email',
10
-            notes: 'Stores the email in memory in a hash and sends confirmation email for signup',
11
-        },
12
-    },
13
-}
14
-
15
-const validators = {
16
-    payload: Joi.object({
17
-        email: Joi.string(),
18
-        name: Joi.string(),
19
-        seeking: Joi.string(),
20
-        sessionToken: Joi.string(),
21
-    }),
22
-}
23
-
24
-module.exports = {
25
-    method: 'POST',
26
-    path: '/send-email/',
27
-    options: {
28
-        ...pluginConfig.docs.get,
29
-        tags: ['api'],
30
-        auth: false,
31
-        cors: true,
32
-        handler: async function (request, h) {
33
-            const { userService } = request.server.services()
34
-            const userCredentials = request.payload
35
-            try {
36
-                const emailSent = await userService.emailSent(userCredentials)
37
-                const hashedSessionToken = Object.keys(
38
-                    userService.activeSessions,
39
-                ).find(hashedToken => {
40
-                    return (
41
-                        userService.activeSessions[`${hashedToken}`].email ===
42
-                        userCredentials.email
43
-                    )
44
-                })
45
-                // Registers the activeSessions object for use by jwt auth strategy
46
-                request.server.app.activeSessions = userService.activeSessions
47
-                if (!hashedSessionToken?.length) {
48
-                    throw Error('hashedSessionToken not Found!!')
49
-                }
50
-                return {
51
-                    ok: true,
52
-                    handler: pluginConfig.handlerType,
53
-                    data: {
54
-                        emailSentSuccessfully: emailSent.wasSuccessfull,
55
-                        hashedSessionToken,
56
-                    },
57
-                }
58
-            } catch (err) {
59
-                console.log('err :=>', err)
60
-                return {
61
-                    ok: false,
62
-                    handler: pluginConfig.handlerType,
63
-                    data: {
64
-                        error: err,
65
-                    },
66
-                }
67
-            }
68
-        },
69
-        validate: {
70
-            ...validators,
71
-            failAction: 'log',
72
-        },
73
-        response: {
74
-            schema: Joi.object({
75
-                ok: Joi.bool(),
76
-                handler: Joi.string(),
77
-                data: Joi.object(),
78
-            }).label('email_res'),
79
-            failAction: 'log',
80
-        },
81
-    },
82
-}

+ 0
- 105
backend/lib/routes/user/signup.js Dosyayı Görüntüle

@@ -1,105 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const errorSchema = require('../../schemas/errors')
5
-const userSchema = require('../../schemas/user')
6
-
7
-const pluginConfig = {
8
-    handlerType: 'user',
9
-    docs: {
10
-        description: 'Create a user',
11
-        notes: 'Create a user and other things',
12
-    },
13
-}
14
-
15
-const validators = {
16
-    post: {
17
-        payload: userSchema.userSignup,
18
-    },
19
-}
20
-
21
-const responseSchemas = {
22
-    response: Joi.object({
23
-        user_id: Joi.number(),
24
-        user_name: Joi.string(),
25
-        user_email: Joi.string(),
26
-        is_poster: Joi.number(),
27
-        is_admin: Joi.number(),
28
-        is_verified: Joi.number(),
29
-    }).label('created_user'),
30
-    error: errorSchema.single,
31
-}
32
-
33
-// Brevo logic will go here,
34
-// send Brevo email with link that has jwt in it?
35
-
36
-module.exports = {
37
-    method: 'POST',
38
-    path: '/signup',
39
-    options: {
40
-        ...pluginConfig.docs,
41
-        tags: ['api'],
42
-        /** Protect this route with authentication? */
43
-        auth: false,
44
-        cors: true,
45
-        handler: async function (request, h) {
46
-            const { userService } = request.server.services()
47
-            const res = request.payload
48
-            const userName = res.user_name
49
-            const userEmail = res.user_email
50
-            const userType = res.is_poster
51
-            const userPw = res.user_pass ? res.user_pass : 'changeme'
52
-            try {
53
-                const user = await userService.signup({
54
-                    password: userPw,
55
-                    userInfo: {
56
-                        user_name: userName,
57
-                        user_email: userEmail,
58
-                        is_poster: userType,
59
-                        is_admin: 0,
60
-                        is_verified: 0,
61
-                    },
62
-                    created_at: Date.now(),
63
-                })
64
-                return h
65
-                    .response({
66
-                        ok: true,
67
-                        handler: pluginConfig.handlerType,
68
-                        data: user,
69
-                    })
70
-                    .code(201)
71
-            } catch (err) {
72
-                console.error('ERROR :=>', err)
73
-                return h
74
-                    .response({
75
-                        ok: false,
76
-                        handler: pluginConfig.handlerType,
77
-                        data: { error: `${err}` },
78
-                    })
79
-                    .code(409)
80
-            }
81
-        },
82
-
83
-        /** Validate based on validators object */
84
-        validate: {
85
-            ...validators.post,
86
-            failAction: 'log',
87
-        },
88
-
89
-        /** Validate the server response */
90
-        response: {
91
-            status: {
92
-                201: Joi.object({
93
-                    ok: Joi.bool(),
94
-                    handler: Joi.string(),
95
-                    data: responseSchemas.response,
96
-                }).label('created_user_res'),
97
-                409: Joi.object({
98
-                    ok: Joi.bool(),
99
-                    handler: Joi.string(),
100
-                    data: responseSchemas.error,
101
-                }).label('error_single_res'),
102
-            },
103
-        },
104
-    },
105
-}

+ 0
- 69
backend/lib/routes/user/token.js Dosyayı Görüntüle

@@ -1,69 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const pluginConfig = {
6
-    handlerType: 'authentication',
7
-    docs: {
8
-        get: {
9
-            description: 'creates session token for authentication',
10
-            notes: 'Creates session token for authentication',
11
-        },
12
-    },
13
-}
14
-
15
-const validators = {
16
-    payload: Joi.object({
17
-        payload: Joi.object({
18
-            email: Joi.string(),
19
-            name: Joi.string(),
20
-            seeking: Joi.string(),
21
-        }),
22
-    }),
23
-}
24
-
25
-module.exports = {
26
-    method: 'POST',
27
-    path: '/token',
28
-    options: {
29
-        ...pluginConfig.docs.get,
30
-        tags: ['api'],
31
-        auth: false,
32
-        cors: {
33
-            headers: ['Authorization', 'Content-Type'],
34
-            exposedHeaders: ['Authorization', 'Access-Control-Expose-Headers'],
35
-        },
36
-        handler: async function (request, h) {
37
-            const { userService } = request.server.services()
38
-            const res = request.payload
39
-            // NOTE: Session Token set for 5 minutes expiration (default)
40
-            const sessionToken = await userService.createToken(res, 600)
41
-            try {
42
-                const response = h.response({
43
-                    ok: true,
44
-                    handler: pluginConfig.handlerType,
45
-                    data: sessionToken,
46
-                })
47
-                response.header('Authorization', sessionToken)
48
-                return response
49
-            } catch (err) {
50
-                return {
51
-                    ok: false,
52
-                    handler: pluginConfig.handlerType,
53
-                    data: {
54
-                        error: err,
55
-                    },
56
-                }
57
-            }
58
-        },
59
-        validate: {
60
-            ...validators,
61
-            failAction: 'log',
62
-        },
63
-        response: {
64
-            // TODO: change back to accommodate new h.response return values
65
-            schema: Joi.any().label('get_session_res'),
66
-            failAction: 'log',
67
-        },
68
-    },
69
-}

+ 0
- 77
backend/lib/routes/user/validate-session.js Dosyayı Görüntüle

@@ -1,77 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const pluginConfig = {
6
-    handlerType: 'jwt',
7
-    docs: {
8
-        get: {
9
-            description: 'validates session token for each step of survey',
10
-            notes: 'Validates session token for each step of survey',
11
-        },
12
-    },
13
-}
14
-
15
-const validators = {
16
-    payload: Joi.string(),
17
-}
18
-
19
-module.exports = {
20
-    method: 'POST',
21
-    path: '/validate-session',
22
-    options: {
23
-        ...pluginConfig.docs.get,
24
-        tags: ['api'],
25
-        auth: false,
26
-        cors: {
27
-            headers: ['Authorization', 'Content-Type'],
28
-            exposedHeaders: ['Authorization', 'Access-Control-Expose-Headers'],
29
-        },
30
-        handler: async function (request, h) {
31
-            const hashedSessionToken = request.payload
32
-            const { userService, profileService } = request.server.services()
33
-            try {
34
-                const validatedSessionToken =
35
-                    userService.validateSession(hashedSessionToken)
36
-                if(validatedSessionToken?.email) throw new Error(`Could not validate token based on payload: ${request.payload}`)
37
-                
38
-                const user = await userService.findByUserEmail(
39
-                    validatedSessionToken.email,
40
-                )
41
-                const type = user.is_poster === 1 ? 'poster' : 'seeker'
42
-                const profiles = await profileService.getCompleteProfilesFor(
43
-                    user.user_id,
44
-                    type,
45
-                )
46
-                // TODO: handle user with multiple profiles...
47
-                const profileId = profiles[0].profile_id
48
-                return {
49
-                    ok: true,
50
-                    handler: pluginConfig.handlerType,
51
-                    data: {
52
-                        ...validatedSessionToken,
53
-                        profileId: profileId,
54
-                    },
55
-                }
56
-            } catch (err) {
57
-                return {
58
-                    ok: false,
59
-                    handler: pluginConfig.handlerType,
60
-                    data: { error: err.message },
61
-                }
62
-            }
63
-        },
64
-        validate: {
65
-            ...validators,
66
-            failAction: 'log',
67
-        },
68
-        response: {
69
-            schema: Joi.object({
70
-                ok: Joi.bool(),
71
-                handler: Joi.string(),
72
-                data: Joi.object(),
73
-            }).label('validate_session_res'),
74
-            failAction: 'log',
75
-        },
76
-    },
77
-}

+ 0
- 90
backend/lib/routes/user/verify-session.js Dosyayı Görüntüle

@@ -1,90 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const pluginConfig = {
6
-    handlerType: 'email',
7
-    docs: {
8
-        get: {
9
-            description: 'verifies confirmation email',
10
-            notes: 'Verifies the email from the stored hash',
11
-        },
12
-    },
13
-}
14
-
15
-const validators = {
16
-    params: Joi.object({
17
-        hashedSessionToken: Joi.string(),
18
-    }),
19
-}
20
-
21
-module.exports = {
22
-    method: 'GET',
23
-    path: '/verify/{hashedSessionToken}',
24
-    options: {
25
-        ...pluginConfig.docs.get,
26
-        tags: ['api'],
27
-        auth: false,
28
-        cors: true,
29
-        handler: async function (request, h) {
30
-            const { userService } = request.server.services()
31
-            const hash = request.params.hashedSessionToken
32
-            try {
33
-                const hashToMatch = Object.keys(
34
-                    userService.activeSessions,
35
-                ).find(hashedToken => {
36
-                    return hashedToken === hash
37
-                })
38
-                if (!hashToMatch?.length) {
39
-                    throw Error('hashToMatch Not Found!')
40
-                }
41
-                const now = Date.now()
42
-                const expiration = new Date(
43
-                    userService.activeSessions[`${hash}`].expiration,
44
-                )
45
-                if (now > expiration) {
46
-                    delete userService.activeSessions[hashToMatch]
47
-                    throw new Error(
48
-                        'you took to long to respond to the email...',
49
-                    )
50
-                }
51
-                if (!hashToMatch) {
52
-                    throw new Error('no record of email in cache')
53
-                }
54
-                // NOTE: When user responds to email,
55
-                // boolean value is set to true, allowing user back into the survey
56
-                userService.activeSessions[
57
-                    hashToMatch
58
-                ].emailWasRespondedTo = true
59
-                return {
60
-                    ok: true,
61
-                    handler: pluginConfig.handlerType,
62
-                    data: {
63
-                        hashesMatch: hashToMatch === hash,
64
-                    },
65
-                }
66
-            } catch (err) {
67
-                console.log('err :=>', err)
68
-                return {
69
-                    ok: false,
70
-                    handler: pluginConfig.handlerType,
71
-                    data: {
72
-                        error: err,
73
-                    },
74
-                }
75
-            }
76
-        },
77
-        validate: {
78
-            ...validators,
79
-            failAction: 'log',
80
-        },
81
-        response: {
82
-            schema: Joi.object({
83
-                ok: Joi.bool(),
84
-                handler: Joi.string(),
85
-                data: Joi.object(),
86
-            }).label('verify_email_res'),
87
-            failAction: 'log',
88
-        },
89
-    },
90
-}

+ 0
- 12
backend/lib/schemas/api.js Dosyayı Görüntüle

@@ -1,12 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const singleApiResponse = Joi.object({
6
-    ok: Joi.bool(),
7
-    handler: Joi.string(),
8
-}).label('api_single')
9
-
10
-module.exports = {
11
-    single: singleApiResponse
12
-}

+ 0
- 13
backend/lib/schemas/authentication.js Dosyayı Görüntüle

@@ -1,13 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const userAuth = Joi.object({
6
-    user_email: Joi.string(),
7
-    created_at: Joi.date(),
8
-    token: Joi.binary().allow(null)
9
-}).label('user_auth')
10
-
11
-module.exports = {
12
-    userAuth
13
-}

+ 0
- 11
backend/lib/schemas/errors.js Dosyayı Görüntüle

@@ -1,11 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const singleError = Joi.object({
6
-    error: Joi.string(),
7
-}).label('error_single')
8
-
9
-module.exports = {
10
-    single: singleError
11
-}

+ 0
- 8
backend/lib/schemas/filter.js Dosyayı Görüntüle

@@ -1,8 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const profileSchema = require('./profiles')
5
-
6
-module.exports = { 
7
-    matchPool: Joi.array().items(profileSchema.single).label('matchPool')
8
-}

+ 0
- 28
backend/lib/schemas/groupings.js Dosyayı Görüntüle

@@ -1,28 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-const surveyProfileSchema = require('./profiles')
5
-
6
-const singleGrouping = Joi.object({
7
-    grouping_id: Joi.number(),
8
-    grouping_name: Joi.string(),
9
-    grouping_type: Joi.string(),
10
-    is_paired: Joi.boolean(),
11
-}).label('grouping_single')
12
-
13
-const singleWithProfile = Joi.object({
14
-    grouping_id: Joi.number(),
15
-    grouping_name: Joi.string(),
16
-    grouping_type: Joi.string(),
17
-    is_paired: Joi.boolean(),
18
-    profile: surveyProfileSchema.single,
19
-}).label('grouping_single_with_profile')
20
-
21
-module.exports = {
22
-    single: singleGrouping,
23
-    singleWithProfile,
24
-    list: Joi.array().items(singleGrouping).label('grouping_list'),
25
-    listWithProfiles: Joi.array()
26
-        .items(singleWithProfile)
27
-        .label('grouping_list_with_profiles'),
28
-}

+ 0
- 10
backend/lib/schemas/health.js Dosyayı Görüntüle

@@ -1,10 +0,0 @@
1
-'use strict'
2
-
3
-const Joi = require('joi')
4
-
5
-const stats = Joi.object({
6
-    date: Joi.string().required(),
7
-    users: Joi.number().required(),
8
-}).label('stats')
9
-
10
-module.exports = { stats }

+ 0
- 0
backend/lib/schemas/memberships.js Dosyayı Görüntüle


Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor

Loading…
İptal
Kaydet