From 6295a238f26643542119c6c3e30cd841e147433c Mon Sep 17 00:00:00 2001 From: Peter Harrison <16875803+palisadoes@users.noreply.github.com> Date: Tue, 30 Jan 2024 12:30:33 -1000 Subject: [PATCH] Revert "Signup route changed" (#1767) --- codegen.ts | 2 - docs/Schema.md | 1427 +++++++---------- package.json | 1 - sample_data/defaultOrganization.json | 22 - sample_data/defaultOrganizationAdmin.json | 26 - sample_data/organizations.json | 29 + sample_data/users.json | 24 + schema.graphql | 2 +- setup.ts | 51 +- src/models/User.ts | 58 - .../Mutation/acceptMembershipRequest.ts | 50 +- src/resolvers/Mutation/signUp.ts | 194 +-- src/typeDefs/inputs.ts | 2 +- src/typeDefs/types.ts | 39 +- src/types/generatedGraphQLTypes.ts | 88 +- src/utilities/loadDefaultOrganization.ts | 82 - tests/helpers/membershipRequests.ts | 8 +- tests/helpers/userAndOrg.ts | 13 - .../Mutation/acceptMembershipRequest.spec.ts | 66 +- tests/resolvers/Mutation/signUp.spec.ts | 52 +- 20 files changed, 734 insertions(+), 1502 deletions(-) delete mode 100644 sample_data/defaultOrganization.json delete mode 100644 sample_data/defaultOrganizationAdmin.json delete mode 100644 src/utilities/loadDefaultOrganization.ts diff --git a/codegen.ts b/codegen.ts index 385ef7a58b..47f6985cad 100644 --- a/codegen.ts +++ b/codegen.ts @@ -78,8 +78,6 @@ const config: CodegenConfig = { UserTag: "../models/OrganizationTagUser#InterfaceOrganizationTagUser", User: "../models/User#InterfaceUser", - - UserToReturn: "../models/User#InterfaceUserToReturn", }, useTypeImports: true, diff --git a/docs/Schema.md b/docs/Schema.md index 0676a40531..04a1dab77e 100644 --- a/docs/Schema.md +++ b/docs/Schema.md @@ -6,10 +6,10 @@ * [Query](#query) * [Mutation](#mutation) * [Objects](#objects) - * [Address](#address) * [Advertisement](#advertisement) * [AggregatePost](#aggregatepost) * [AggregateUser](#aggregateuser) + * [AndroidFirebaseOptions](#androidfirebaseoptions) * [AuthData](#authdata) * [CheckIn](#checkin) * [CheckInStatus](#checkinstatus) @@ -20,11 +20,13 @@ * [DirectChatMessage](#directchatmessage) * [Donation](#donation) * [Event](#event) + * [EventProject](#eventproject) * [ExtendSession](#extendsession) * [Feedback](#feedback) * [Group](#group) * [GroupChat](#groupchat) * [GroupChatMessage](#groupchatmessage) + * [IOSFirebaseOptions](#iosfirebaseoptions) * [InvalidCursor](#invalidcursor) * [Language](#language) * [LanguageModel](#languagemodel) @@ -45,24 +47,21 @@ * [Post](#post) * [PostConnection](#postconnection) * [Subscription](#subscription) + * [Task](#task) * [Translation](#translation) * [UnauthenticatedError](#unauthenticatederror) * [UnauthorizedError](#unauthorizederror) - * [UpdateAdvertisementPayload](#updateadvertisementpayload) * [User](#user) * [UserConnection](#userconnection) * [UserCustomData](#usercustomdata) * [UserEdge](#useredge) - * [UserPhone](#userphone) * [UserTag](#usertag) * [UserTagEdge](#usertagedge) * [UserTagsConnection](#usertagsconnection) * [UserTagsConnectionResult](#usertagsconnectionresult) - * [UserToReturn](#usertoreturn) * [UsersConnection](#usersconnection) * [UsersConnectionResult](#usersconnectionresult) * [Inputs](#inputs) - * [AddressInput](#addressinput) * [CheckInInput](#checkininput) * [CommentInput](#commentinput) * [CreateUserTagInput](#createusertaginput) @@ -70,6 +69,7 @@ * [DonationWhereInput](#donationwhereinput) * [EventAttendeeInput](#eventattendeeinput) * [EventInput](#eventinput) + * [EventProjectInput](#eventprojectinput) * [EventWhereInput](#eventwhereinput) * [FeedbackInput](#feedbackinput) * [ForgotPasswordData](#forgotpassworddata) @@ -85,41 +85,37 @@ * [PostUpdateInput](#postupdateinput) * [PostWhereInput](#postwhereinput) * [RecaptchaVerification](#recaptchaverification) + * [TaskInput](#taskinput) * [ToggleUserTagAssignInput](#toggleusertagassigninput) - * [UpdateAdvertisementInput](#updateadvertisementinput) * [UpdateEventInput](#updateeventinput) + * [UpdateEventProjectInput](#updateeventprojectinput) * [UpdateOrganizationInput](#updateorganizationinput) + * [UpdateTaskInput](#updatetaskinput) * [UpdateUserInput](#updateuserinput) * [UpdateUserPasswordInput](#updateuserpasswordinput) * [UpdateUserTagInput](#updateusertaginput) * [UpdateUserTypeInput](#updateusertypeinput) * [UserAndOrganizationInput](#userandorganizationinput) * [UserInput](#userinput) - * [UserPhoneInput](#userphoneinput) * [UserTagsConnectionInput](#usertagsconnectioninput) * [UserWhereInput](#userwhereinput) * [UsersConnectionInput](#usersconnectioninput) * [createChatInput](#createchatinput) * [createGroupChatInput](#creategroupchatinput) * [Enums](#enums) - * [AdvertisementType](#advertisementtype) - * [EducationGrade](#educationgrade) - * [EmploymentStatus](#employmentstatus) * [EventOrderByInput](#eventorderbyinput) - * [Gender](#gender) - * [MaritalStatus](#maritalstatus) * [OrganizationOrderByInput](#organizationorderbyinput) * [PaginationDirection](#paginationdirection) * [PostOrderByInput](#postorderbyinput) * [Recurrance](#recurrance) * [Status](#status) + * [TaskOrderByInput](#taskorderbyinput) * [Type](#type) * [UserOrderByInput](#userorderbyinput) * [UserType](#usertype) * [Scalars](#scalars) * [Any](#any) * [Boolean](#boolean) - * [CountryCode](#countrycode) * [Date](#date) * [DateTime](#datetime) * [EmailAddress](#emailaddress) @@ -924,6 +920,16 @@ +createEventProject +EventProject! + + + +data +EventProjectInput! + + + createGroupChat GroupChat! @@ -1049,6 +1055,21 @@ +createTask +Task! + + + +data +TaskInput! + + + +eventProjectId +ID! + + + deleteAdvertisementById DeletePayload! @@ -1264,6 +1285,16 @@ +removeEventProject +EventProject! + + + +id +ID! + + + removeGroupChat GroupChat! @@ -1349,6 +1380,16 @@ +removeTask +Task + + + +id +ID! + + + removeUserFromGroupChat GroupChat! @@ -1424,6 +1465,21 @@ +setTaskVolunteers +Task + + + +id +ID! + + + +volunteers +[ID]! + + + signUp AuthData! @@ -1504,18 +1560,23 @@ -updateAdvertisement -UpdateAdvertisementPayload +updateEvent +Event! -input -UpdateAdvertisementInput! +id +ID! -updateEvent -Event! +data +UpdateEventInput + + + +updateEventProject +EventProject! @@ -1525,7 +1586,7 @@ data -UpdateEventInput +UpdateEventProjectInput! @@ -1599,6 +1660,21 @@ +updateTask +Task + + + +id +ID! + + + +data +UpdateTaskInput! + + + updateUserProfile User! @@ -1658,61 +1734,6 @@ ## Objects -### Address - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FieldArgumentTypeDescription
cityString
countryCodeCountryCode
dependentLocalityString
line1String
line2String
postalCodeString
sortingCodeString
stateString
- ### Advertisement @@ -1727,7 +1748,7 @@ - + @@ -1737,7 +1758,7 @@ - + @@ -1747,7 +1768,7 @@ - + @@ -1760,25 +1781,30 @@ + +
_idID!ID
orgIdID!ID
typeAdvertisementType!String!
Date!
+ +### AggregatePost + + + - - - - - - - - + + + + + + - - + +
createdAtDateTime!
creatorUserFieldArgumentTypeDescription
updatedAtDateTime!countInt!
-### AggregatePost +### AggregateUser @@ -1798,7 +1824,7 @@
-### AggregateUser +### AndroidFirebaseOptions @@ -1811,8 +1837,28 @@ - - + + + + + + + + + + + + + + + + + + + + + + @@ -1832,7 +1878,7 @@ - + @@ -1845,6 +1891,16 @@ + + + + + + + + + +
countInt!apiKeyString
appIdString
messagingSenderIdString
projectIdString
storageBucketString
userUserToReturn!User!
String!
androidFirebaseOptionsAndroidFirebaseOptions!
iosFirebaseOptionsIOSFirebaseOptions!
@@ -1895,16 +1951,6 @@ Boolean! - -createdAt -DateTime! - - - -updatedAt -DateTime! - - @@ -1952,7 +1998,7 @@ _id -ID! +ID @@ -1961,33 +2007,28 @@ -post -Post! - - - -likedBy -[User] +createdAt +DateTime -likeCount -Int +creator +User! -creator -User +post +Post! -createdAt -DateTime! +likedBy +[User] -updatedAt -DateTime! +likeCount +Int @@ -2077,17 +2118,7 @@ creator -User - - - -createdAt -DateTime! - - - -updatedAt -DateTime! +User! @@ -2136,11 +2167,6 @@ -updatedAt -DateTime! - - - messageContent String! @@ -2195,16 +2221,6 @@ Float! - -createdAt -DateTime! - - - -updatedAt -DateTime! - - @@ -2302,22 +2318,12 @@ creator -User - - - -createdAt -DateTime! - - - -updatedAt -DateTime! +User! attendees -[User] +[User!]! @@ -2327,7 +2333,7 @@ admins -[User!] +[User] @@ -2341,6 +2347,11 @@ +projects +[EventProject] + + + feedback [Feedback!]! @@ -2353,7 +2364,7 @@ -### ExtendSession +### EventProject @@ -2366,16 +2377,56 @@ - - + + - + - + + + + + + + + + + + + + + + + +
accessTokenString!_idID!
refreshTokentitle String!
descriptionString!
eventEvent!
tasks[Task]
+ +### ExtendSession + + + + + + + + + + + + + + + + + + + + + +
FieldArgumentTypeDescription
accessTokenString!
refreshTokenString!
### Feedback @@ -2410,16 +2461,6 @@ String - -createdAt -DateTime! - - - -updatedAt -DateTime! - - @@ -2437,12 +2478,12 @@ _id -ID! +ID title -String! +String @@ -2452,12 +2493,7 @@ createdAt -DateTime! - - - -updatedAt -DateTime! +DateTime @@ -2467,7 +2503,7 @@ admins -[User!]! +[User] @@ -2502,17 +2538,7 @@ creator -User - - - -createdAt -DateTime! - - - -updatedAt -DateTime! +User! @@ -2556,13 +2582,58 @@ -updatedAt -DateTime! +messageContent +String! + + + +### IOSFirebaseOptions + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2772,17 +2843,12 @@ - + - - - - - - + @@ -2845,11 +2911,6 @@ - - - - -
messageContentString!FieldArgumentTypeDescription
apiKeyString
appIdString
messagingSenderIdString
projectIdString
storageBucketString
iosClientIdString
iosBundleIdString
textString!String
createdAtDateTime!
updatedAtDateTime!DateTime
DateTime!
updatedAtDateTime!
@@ -2946,18 +3007,13 @@ -creator -User - - - -createdAt -DateTime! +isPublic +Boolean! -updatedAt -DateTime! +creator +User! @@ -2967,7 +3023,7 @@ admins -[User!] +[User] @@ -2981,8 +3037,8 @@ -userRegistrationRequired -Boolean! +blockedUsers +[User] @@ -2991,13 +3047,13 @@ -blockedUsers -[User] +apiUrl +URL! -apiUrl -URL! +createdAt +DateTime @@ -3106,23 +3162,23 @@ -creator -User +isPublic +Boolean! -apiUrl -URL! +creator +User! -userRegistrationRequired +visibleInSearch Boolean! -visibleInSearch -Boolean! +apiUrl +URL! @@ -3237,7 +3293,7 @@ When paginating backwards, are there more items? uninstalledOrgs -[ID!] +[ID!]! @@ -3272,7 +3328,7 @@ When paginating backwards, are there more items? createdAt -DateTime! +DateTime @@ -3307,17 +3363,7 @@ When paginating backwards, are there more items? createdAt -DateTime! - - - -creator -User - - - -updatedAt -DateTime! +DateTime @@ -3331,6 +3377,11 @@ When paginating backwards, are there more items? +creator +User! + + + organization Organization! @@ -3438,7 +3489,7 @@ A list of edges. -### Translation +### Task @@ -3451,29 +3502,54 @@ A list of edges. - - + + - - + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + +
lang_codeString_idID!
en_valueStringtitleString!
translationdescription String
verifiedeventEvent!
creatorUser!
createdAtDateTime!
completed Boolean
deadlineDateTime
volunteers[User]
-### UnauthenticatedError +### Translation @@ -3486,14 +3562,29 @@ A list of edges. - - + + + + + + + + + + + + + + + + +
messageString!lang_codeString
en_valueString
translationString
verifiedBoolean
-### UnauthorizedError +### UnauthenticatedError @@ -3513,7 +3604,7 @@ A list of edges.
-### UpdateAdvertisementPayload +### UnauthorizedError @@ -3526,8 +3617,8 @@ A list of edges. - - + + @@ -3546,43 +3637,38 @@ A list of edges. + + + + + - - + + - - + + - - + + - - - - - - - - - - - - + + - - + + @@ -3591,18 +3677,18 @@ A list of edges. - - + + - - + + - - + + @@ -3611,58 +3697,48 @@ A list of edges. - - - - - - - + + - - + + - + - - + + - - + + - - + + - - + + - - + + - - - - - - - + + @@ -3695,21 +3771,6 @@ A list of edges. - - - - - - - - - - - - - - -
advertisementAdvertisementmessageString!
tokenVersionInt!
_id ID!
addressAddressfirstNameString!
adminApprovedBooleanlastNameString!
adminFor[Organization]emailEmailAddress!
appLanguageCodeString!
birthDateDate
createdAtDateTime!userTypeString
createdEvents[Event]appLanguageCodeString!
educationGradeEducationGradejoinedOrganizations[Organization]
emailEmailAddress!createdEvents[Event]
employmentStatusEmploymentStatusregisteredEvents[Event]
firstNameString!
genderGenderadminFor[Organization]
imageStringmembershipRequests[MembershipRequest]
joinedOrganizationsorganizationsBlockedBy [Organization]
lastNameString!imageString
maritalStatusMaritalStatusorganizationUserBelongsToOrganization
membershipRequests[MembershipRequest]pluginCreationAllowedBoolean
organizationsBlockedBy[Organization]adminApprovedBoolean
phoneUserPhoneassignedTasks[Task]
pluginCreationAllowedBoolean!
registeredEvents[Event]createdAtDateTime
ID
tokenVersionInt!
updatedAtDateTime!
userTypeUserType!
@@ -3803,36 +3864,6 @@ A list of edges. -### UserPhone - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FieldArgumentTypeDescription
homePhoneNumber
mobilePhoneNumber
workPhoneNumber
- ### UserTag @@ -3963,186 +3994,6 @@ A list of edges.
-### UserToReturn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FieldArgumentTypeDescription
_idID!
addressAddress
adminApprovedBoolean
adminFor[Organization]
appLanguageCodeString!
birthDateDate
createdAtDateTime!
createdEvents[Event]
createdOrganizations[Organization]
educationGradeEducationGrade
emailEmailAddress!
employmentStatusEmploymentStatus
eventAdmin[Event]
firstNameString!
genderGender
imageString
joinedOrganizations[Organization]
lastNameString!
maritalStatusMaritalStatus
membershipRequests[MembershipRequest]
organizationsBlockedBy[Organization]
phoneUserPhone
pluginCreationAllowedBoolean!
registeredEvents[Event]
tagsAssignedWithUserTagsConnection
afterString
beforeString
firstPositiveInt
lastPositiveInt
organizationIdID
tokenVersionInt!
updatedAtDateTime!
userTypeUserType!
- ### UsersConnection @@ -4195,60 +4046,6 @@ A list of edges. ## Inputs -### AddressInput - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FieldTypeDescription
cityString
countryCodeCountryCode
dependentLocalityString
line1String
line2String
postalCodeString
sortingCodeString
stateString
- ### CheckInInput @@ -4547,6 +4344,35 @@ A list of edges.
+### EventProjectInput + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldTypeDescription
titleString!
descriptionString!
eventIdID!
+ ### EventWhereInput @@ -4872,23 +4698,23 @@ A list of edges. - - + + - - + + - - + + - - + + @@ -5026,12 +4852,12 @@ A list of edges. - + - + @@ -5307,7 +5133,7 @@ A list of edges.
apiUrlURLisPublicBoolean!
imageStringvisibleInSearchBoolean!
userRegistrationRequiredBooleanapiUrlURL
visibleInSearchBooleanimageString
userRegistrationRequiredvisibleInSearch Boolean
visibleInSearchisPublic Boolean
-### ToggleUserTagAssignInput +### TaskInput @@ -5319,19 +5145,24 @@ A list of edges. - - + + - - + + + + + + +
userIdID!titleString!
tagIdID!descriptionString!
deadlineDateTime!
-### UpdateAdvertisementInput +### ToggleUserTagAssignInput @@ -5343,33 +5174,13 @@ A list of edges. - + - - - - - - - - - - - - - - - - - - - - - - + + @@ -5459,7 +5270,7 @@ A list of edges.
_iduserId ID!
nameString
linkString
typeAdvertisementType
startDateDate
endDateDatetagIdID!
-### UpdateOrganizationInput +### UpdateEventProjectInput @@ -5471,7 +5282,7 @@ A list of edges. - + @@ -5480,13 +5291,32 @@ A list of edges. + +
nametitle String
String
+ +### UpdateOrganizationInput + + + + + + + + + + + + + + + - + - + @@ -5495,10 +5325,15 @@ A list of edges. + + + + +
FieldTypeDescription
nameString
locationdescription String
userRegistrationRequiredisPublic Boolean
Boolean
locationString
-### UpdateUserInput +### UpdateTaskInput @@ -5510,53 +5345,52 @@ A list of edges. - - + + - - + + - - + + - - + + + +
addressAddressInputtitleString
birthDateDatedescriptionString
educationGradeEducationGradedeadlineDateTime
emailEmailAddresscompletedBoolean
+ +### UpdateUserInput + + + - - - + + + + + - - - - - - - - - - - - + + @@ -5700,37 +5534,8 @@ A list of edges. - - - - - -
employmentStatusEmploymentStatusFieldTypeDescription
firstName String
genderGender
lastName String
maritalStatusMaritalStatus
phoneUserPhoneInputemailEmailAddress
selectedOrgainzationID!
- -### UserPhoneInput - - - - - - - - - - - - - - - - - - - - - - - + + @@ -6023,127 +5828,6 @@ A list of edges. ## Enums -### AdvertisementType - -
FieldTypeDescription
homePhoneNumber
mobilePhoneNumber
workPhoneNumberorganizationUserBelongsToIdID
- - - - - - - - - - - - - - - - - - -
ValueDescription
BANNER
POPUP
MENU
- -### EducationGrade - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ValueDescription
NO_GRADE
PRE_KG
KG
GRADE_1
GRADE_2
GRADE_3
GRADE_4
GRADE_5
GRADE_6
GRADE_7
GRADE_8
GRADE_9
GRADE_10
GRADE_11
GRADE_12
GRADUATE
- -### EmploymentStatus - - - - - - - - - - - - - - - - - - - - -
ValueDescription
FULL_TIME
PART_TIME
UNEMPLOYED
- ### EventOrderByInput @@ -6235,64 +5919,6 @@ A list of edges.
-### Gender - - - - - - - - - - - - - - - - - - - - -
ValueDescription
MALE
FEMALE
OTHER
- -### MaritalStatus - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ValueDescription
SINGLE
ENGAGED
MARRIED
DIVORCED
WIDOWED
SEPERATED
- ### OrganizationOrderByInput @@ -6326,14 +5952,6 @@ A list of edges. - - - - - - - - @@ -6492,6 +6110,57 @@ A list of edges.
createdAt_ASC
createdAt_DESC
apiUrl_ASC
+### TaskOrderByInput + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueDescription
id_ASC
id_DESC
title_ASC
title_DESC
description_ASC
description_DESC
createdAt_ASC
createdAt_DESC
deadline_ASC
deadline_DESC
+ ### Type @@ -6582,10 +6251,6 @@ A list of edges. - - - -
SUPERADMIN
NON_USER
@@ -6597,8 +6262,6 @@ A list of edges. The `Boolean` scalar type represents `true` or `false`. -### CountryCode - ### Date A date string, such as 2007-12-03, compliant with the `full-date` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar. diff --git a/package.json b/package.json index 8a2730fec4..c573c79a0e 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,6 @@ "generate:graphql-schema": "get-graphql-schema http://localhost:4000/graphql --json > docs/schema.json", "generate:ssl-private-key": "openssl genrsa -out ./key.pem", "import:sample-data": "ts-node ./src/utilities/loadSampleData.ts", - "import:sample-data-defaultOrg": "ts-node ./src/utilities/loadDefaultOrganization.ts", "import:sample-data:prod": "node ./build/utilities/loadSampleData.js", "gen:schema": "graphql-inspector introspect ./src/typeDefs/**/**/*.ts --write ./schema.graphql ", "update:toc": "node scripts/githooks/update-toc.js" diff --git a/sample_data/defaultOrganization.json b/sample_data/defaultOrganization.json deleted file mode 100644 index 4326c60518..0000000000 --- a/sample_data/defaultOrganization.json +++ /dev/null @@ -1,22 +0,0 @@ -[ - { - "_id": "6437904485008f171cf29924", - "status": "ACTIVE", - "members": ["64378abd85008f171cf2990d"], - "admins": ["64378abd85008f171cf2990d"], - "groupChats": [], - "posts": [], - "pinnedPosts": [], - "membershipRequests": [], - "blockedUsers": [], - "name": "DEFAULT ORGANIZATION", - "description": "The default organization which will be always in DB.", - "location": "Delhi, India", - "userRegistrationRequired": true, - "visibleInSearch": true, - "image": null, - "creatorId": "64378abd85008f171cf2990d", - "createdAt": "2023-04-13T05:16:52.827Z", - "__v": 0 - } -] diff --git a/sample_data/defaultOrganizationAdmin.json b/sample_data/defaultOrganizationAdmin.json deleted file mode 100644 index 1ae8abbd53..0000000000 --- a/sample_data/defaultOrganizationAdmin.json +++ /dev/null @@ -1,26 +0,0 @@ -[ - { - "_id": "64378abd85008f171cf2990d", - "tokenVersion": 0, - "appLanguageCode": "en", - "createdOrganizations": ["6437904485008f171cf29924"], - "createdEvents": [], - "userType": "SUPERADMIN", - "joinedOrganizations": ["6437904485008f171cf29924"], - "registeredEvents": [], - "eventAdmin": [], - "adminFor": ["6437904485008f171cf29924"], - "membershipRequests": [], - "organizationsBlockedBy": [], - "status": "ACTIVE", - "pluginCreationAllowed": true, - "adminApproved": true, - "firstName": "Wilt", - "lastName": "Shepherd", - "email": "testsuperadmin@example.com", - "password": "$2a$12$bSYpay6TRMpTOaAmYPFXku4avwmqfFBtmgg39TabxmtFEiz4plFtW", - "image": null, - "createdAt": "2023-04-13T04:53:17.742Z", - "__v": 0 - } -] diff --git a/sample_data/organizations.json b/sample_data/organizations.json index b46bb36047..f57ceab8bb 100644 --- a/sample_data/organizations.json +++ b/sample_data/organizations.json @@ -1,4 +1,33 @@ [ + { + "_id": "6437904485008f171cf29924", + "status": "ACTIVE", + "members": ["64378abd85008f171cf2990d"], + "admins": ["64378abd85008f171cf2990d"], + "groupChats": [], + "posts": [], + "pinnedPosts": [], + "membershipRequests": [], + "blockedUsers": [], + "name": "The Unity Foundation", + "description": "A foundation aimed at uniting the world and making it a better place for all.", + "address": { + "city": "Delhi", + "countryCode": "IN", + "dependentLocality": "Some Dependent Locality", + "line1": "123 Random Street", + "line2": "Apartment 456", + "postalCode": "110001", + "sortingCode": "ABC-123", + "state": "Delhi" + }, + "userRegistrationRequired": false, + "visibleInSearch": true, + "image": null, + "creatorId": "64378abd85008f171cf2990d", + "createdAt": "2023-04-13T05:16:52.827Z", + "__v": 0 + }, { "_id": "6537904485008f171cf29924", "status": "ACTIVE", diff --git a/sample_data/users.json b/sample_data/users.json index f5f921a55d..d3fa89a564 100644 --- a/sample_data/users.json +++ b/sample_data/users.json @@ -1,4 +1,28 @@ [ + { + "_id": "64378abd85008f171cf2990d", + "tokenVersion": 0, + "appLanguageCode": "en", + "createdOrganizations": ["6437904485008f171cf29924"], + "createdEvents": [], + "userType": "SUPERADMIN", + "joinedOrganizations": ["6437904485008f171cf29924"], + "registeredEvents": [], + "eventAdmin": [], + "adminFor": ["6437904485008f171cf29924"], + "membershipRequests": [], + "organizationsBlockedBy": [], + "status": "ACTIVE", + "pluginCreationAllowed": true, + "adminApproved": true, + "firstName": "Wilt", + "lastName": "Shepherd", + "email": "testsuperadmin@example.com", + "password": "$2a$12$bSYpay6TRMpTOaAmYPFXku4avwmqfFBtmgg39TabxmtFEiz4plFtW", + "image": null, + "createdAt": "2023-04-13T04:53:17.742Z", + "__v": 0 + }, { "_id": "65378abd85008f171cf2990d", "tokenVersion": 0, diff --git a/schema.graphql b/schema.graphql index 6afaa3480b..bc8d557437 100644 --- a/schema.graphql +++ b/schema.graphql @@ -56,7 +56,7 @@ scalar Any type AuthData { accessToken: String! refreshToken: String! - user: UserToReturn! + user: User! } type CheckIn { diff --git a/setup.ts b/setup.ts index e9a7932d52..035fbbf349 100644 --- a/setup.ts +++ b/setup.ts @@ -746,54 +746,6 @@ async function importData(): Promise { } } -//Import sample data -/** - * The function `importDefaultOrganization` will import the default organization - * with wiping of existing data. - * @returns The function returns a Promise that resolves to `void`. - */ - -async function importDefaultOrganization(): Promise { - return new Promise(async (resolve, reject) => { - if (!process.env.MONGO_DB_URL) { - console.log("Couldn't find mongodb url"); - return; - } - const client = new mongodb.MongoClient(process.env.MONGO_DB_URL, { - useNewUrlParser: true, - useUnifiedTopology: true, - }); - try { - await client.connect(); - const db = client.db(); - const collections = await db.listCollections().toArray(); - if (collections.length > 0) { - resolve; - } else { - await exec( - "npm run import:sample-data-defaultOrg", - (error: ExecException | null, stdout: string, stderr: string) => { - if (error) { - console.error(`Error: ${error.message}`); - abort(); - } - if (stderr) { - console.error(`Error: ${stderr}`); - abort(); - } - console.log(`Output: ${stdout}`); - resolve; - } - ); - } - client.close(); - } catch (e: any) { - console.log(`Couldn't import the default Organization`); - reject; - } - }); -} - type VerifySmtpConnectionReturnType = { success: boolean; error: unknown; @@ -1158,10 +1110,9 @@ async function main(): Promise { default: false, }, ]); + if (shouldRunDataImport) { await importData(); - } else { - await importDefaultOrganization(); } } diff --git a/src/models/User.ts b/src/models/User.ts index a750e567f6..8f8eb098be 100644 --- a/src/models/User.ts +++ b/src/models/User.ts @@ -283,70 +283,12 @@ const userSchema = new Schema( userSchema.plugin(mongoosePaginate); -/** - * This is an interface of the user that will be returned to the client side. - * The differrence between this interface and the real User Interface is that it doesn't contains password field - * Although this is a poor way, a better way will include implementing this Model with inclusion of password field and then using that model everywhere. - */ -export interface InterfaceUserToReturn { - _id: Types.ObjectId; - address: { - city: string; - countryCode: string; - dependentLocality: string; - line1: string; - line2: string; - postalCode: string; - sortingCode: string; - state: string; - }; - adminApproved: boolean; - adminFor: PopulatedDoc[]; - appLanguageCode: string; - birthDate: Date; - createdAt: Date; - createdEvents: PopulatedDoc[]; - createdOrganizations: PopulatedDoc[]; - educationGrade: string; - email: string; - employmentStatus: string; - eventAdmin: PopulatedDoc[]; - firstName: string; - gender: string; - image: string | undefined | null; - joinedOrganizations: PopulatedDoc[]; - lastName: string; - maritalStatus: string; - membershipRequests: PopulatedDoc[]; - organizationsBlockedBy: PopulatedDoc[]; - phone: { - home: string; - mobile: string; - work: string; - }; - pluginCreationAllowed: boolean; - registeredEvents: PopulatedDoc[]; - status: string; - token: string | undefined; - tokenVersion: number; - updatedAt: Date; - userType: string; -} - const userModel = (): PaginateModel => model>("User", userSchema); -const userToReturnModel = (): PaginateModel => - model>( - "UserToReturn", - userSchema - ); - createLoggingMiddleware(userSchema, "User"); // This syntax is needed to prevent Mongoose OverwriteModelError while running tests. export const User = (models.User || userModel()) as ReturnType< typeof userModel >; -export const UserToReturn = (models.UserToReturn || - userToReturnModel()) as ReturnType; diff --git a/src/resolvers/Mutation/acceptMembershipRequest.ts b/src/resolvers/Mutation/acceptMembershipRequest.ts index 3e39f15932..18d650cd14 100644 --- a/src/resolvers/Mutation/acceptMembershipRequest.ts +++ b/src/resolvers/Mutation/acceptMembershipRequest.ts @@ -21,7 +21,6 @@ import { cacheOrganizations } from "../../services/OrganizationCache/cacheOrgani * 3. Whether the user exists * 4. whether currentUser with _id === context.userId is an admin of organization. * 5. Whether user is already a member of organization. - * 6. Whether the user is a new user or not */ export const acceptMembershipRequest: MutationResolvers["acceptMembershipRequest"] = async (_parent, args, context) => { @@ -103,39 +102,22 @@ export const acceptMembershipRequest: MutationResolvers["acceptMembershipRequest if (updatedOrganization !== null) { await cacheOrganizations([updatedOrganization]); - // If adminAprooved is false, it means it is the very first request or a very fresh member has made the request! Hence we need to update this variable also - if (user.adminApproved == false) { - await User.updateOne( - { - _id: user._id, - }, - { - $set: { - adminApproved: true, - }, - $push: { - joinedOrganizations: organization._id, - }, - $pull: { - membershipRequests: membershipRequest._id, - }, - } - ); - } else { - await User.updateOne( - { - _id: user._id, - }, - { - $push: { - joinedOrganizations: organization._id, - }, - $pull: { - membershipRequests: membershipRequest._id, - }, - } - ); - } } + + // Update the user + await User.updateOne( + { + _id: user._id, + }, + { + $push: { + joinedOrganizations: organization._id, + }, + $pull: { + membershipRequests: membershipRequest._id, + }, + } + ); + return membershipRequest; }; diff --git a/src/resolvers/Mutation/signUp.ts b/src/resolvers/Mutation/signUp.ts index abc932677c..1ef2131566 100644 --- a/src/resolvers/Mutation/signUp.ts +++ b/src/resolvers/Mutation/signUp.ts @@ -8,8 +8,7 @@ import { } from "../../constants"; import type { MutationResolvers } from "../../types/generatedGraphQLTypes"; import { errors, requestContext } from "../../libraries"; -import type { InterfaceUser } from "../../models"; -import { User, Organization, MembershipRequest } from "../../models"; +import { User, Organization } from "../../models"; import { createAccessToken, createRefreshToken, @@ -18,8 +17,6 @@ import { import { uploadEncodedImage } from "../../utilities/encodedImageStorage/uploadEncodedImage"; import { cacheOrganizations } from "../../services/OrganizationCache/cacheOrganizations"; import { findOrganizationsInCache } from "../../services/OrganizationCache/findOrganizationsInCache"; -import type { Document } from "mongoose"; -import { omit } from "lodash"; //import { isValidString } from "../../libraries/validators/validateString"; //import { validatePassword } from "../../libraries/validators/validatePassword"; /** @@ -41,21 +38,77 @@ export const signUp: MutationResolvers["signUp"] = async (_parent, args) => { ); } + // TODO: this check is to be removed let organization; + if (args.data.organizationUserBelongsToId) { + const organizationFoundInCache = await findOrganizationsInCache([ + args.data.organizationUserBelongsToId, + ]); - const organizationFoundInCache = await findOrganizationsInCache([ - args.data.selectedOrgainzation, - ]); + organization = organizationFoundInCache[0]; - organization = organizationFoundInCache[0]; - if (organizationFoundInCache[0] == null) { - organization = await Organization.findOne({ - _id: args.data.selectedOrgainzation, - }).lean(); + if (organizationFoundInCache[0] == null) { + organization = await Organization.findOne({ + _id: args.data.organizationUserBelongsToId, + }).lean(); + + await cacheOrganizations([organization!]); + } + + if (!organization) { + throw new errors.NotFoundError( + requestContext.translate(ORGANIZATION_NOT_FOUND_ERROR.MESSAGE), + ORGANIZATION_NOT_FOUND_ERROR.CODE, + ORGANIZATION_NOT_FOUND_ERROR.PARAM + ); + } } - const isLastResortSuperAdmin = - args.data.email === LAST_RESORT_SUPERADMIN_EMAIL; + // // Checks if the recieved arguments are valid according to standard input norms + // const validationResult_firstName = isValidString(args.data!.firstName, 50); + // const validationResult_lastName = isValidString(args.data!.lastName, 50); + // const validationResult_Password = validatePassword(args.data!.password!); + // if (!validationResult_firstName.isFollowingPattern) { + // throw new errors.InputValidationError( + // requestContext.translate( + // `${REGEX_VALIDATION_ERROR.message} in first name` + // ), + // REGEX_VALIDATION_ERROR.code + // ); + // } + // if (!validationResult_firstName.isLessThanMaxLength) { + // throw new errors.InputValidationError( + // requestContext.translate( + // `${LENGTH_VALIDATION_ERROR.message} 50 characters in first name` + // ), + // LENGTH_VALIDATION_ERROR.code + // ); + // } + // if (!validationResult_lastName.isFollowingPattern) { + // throw new errors.InputValidationError( + // requestContext.translate( + // `${REGEX_VALIDATION_ERROR.message} in last name` + // ), + // REGEX_VALIDATION_ERROR.code + // ); + // } + // if (!validationResult_lastName.isLessThanMaxLength) { + // throw new errors.InputValidationError( + // requestContext.translate( + // `${LENGTH_VALIDATION_ERROR.message} 50 characters in last name` + // ), + // LENGTH_VALIDATION_ERROR.code + // ); + // } + // if (!validationResult_Password) { + // throw new errors.InputValidationError( + // requestContext.translate( + // `The password must contain a mixture of uppercase, lowercase, numbers, and symbols and must be greater than 8, and less than 50 characters` + // ), + // `Invalid Password` + // ); + // } + const hashedPassword = await bcrypt.hash(args.data.password, 12); // Upload file @@ -63,106 +116,33 @@ export const signUp: MutationResolvers["signUp"] = async (_parent, args) => { if (args.file) { uploadImageFileName = await uploadEncodedImage(args.file, null); } - let createdUser: (InterfaceUser & Document) | null; - - if (organization !== null) { - await cacheOrganizations([organization]); - // If organization requested by user is a public organization, then no need of creating a membership request - - if (organization.userRegistrationRequired == false) { - createdUser = await User.create({ - ...args.data, - email: args.data.email.toLowerCase(), // ensure all emails are stored as lowercase to prevent duplicated due to comparison errors - image: uploadImageFileName ? uploadImageFileName : null, - password: hashedPassword, - userType: isLastResortSuperAdmin ? "SUPERADMIN" : "USER", - adminApproved: true, - joinedOrganizations: [args.data.selectedOrgainzation], - }); - // Update the organization - await Organization.findOneAndUpdate( - { - _id: organization._id, - }, - { - $push: { - members: createdUser._id, - }, - }, - { - new: true, - } - ); - } else { - createdUser = await User.create({ - ...args.data, - email: args.data.email.toLowerCase(), // ensure all emails are stored as lowercase to prevent duplicated due to comparison errors - image: uploadImageFileName ? uploadImageFileName : null, - password: hashedPassword, - userType: isLastResortSuperAdmin ? "SUPERADMIN" : "USER", - adminApproved: isLastResortSuperAdmin, - }); - - // A membership request will be made to the organization - const createdMembershipRequest = await MembershipRequest.create({ - user: createdUser._id, - organization: organization._id, - }); - - const updatedOrganization = await Organization.findOneAndUpdate( - { - _id: organization._id, - }, - { - $push: { - membershipRequests: createdMembershipRequest._id, - }, - }, - { - new: true, - } - ).lean(); - - if (updatedOrganization !== null) { - await cacheOrganizations([updatedOrganization]); - } - - createdUser = await User.findOneAndUpdate( - { - _id: createdUser._id, - }, - { - $push: { - membershipRequests: createdMembershipRequest._id, - }, - }, - { - new: true, - } - ); - } - } else { - throw new errors.NotFoundError( - requestContext.translate(ORGANIZATION_NOT_FOUND_ERROR.MESSAGE), - ORGANIZATION_NOT_FOUND_ERROR.CODE, - ORGANIZATION_NOT_FOUND_ERROR.PARAM - ); - } - const accessToken = await createAccessToken(createdUser!); - const refreshToken = await createRefreshToken(createdUser!); + const isLastResortSuperAdmin = + args.data.email === LAST_RESORT_SUPERADMIN_EMAIL; + + const createdUser = await User.create({ + ...args.data, + email: args.data.email.toLowerCase(), // ensure all emails are stored as lowercase to prevent duplicated due to comparison errors + image: uploadImageFileName ? uploadImageFileName : null, + password: hashedPassword, + userType: isLastResortSuperAdmin ? "SUPERADMIN" : "USER", + adminApproved: isLastResortSuperAdmin, + }); + + const accessToken = await createAccessToken(createdUser); + const refreshToken = await createRefreshToken(createdUser); copyToClipboard(`{ - "Authorization": "Bearer ${accessToken}" -}`); + "Authorization": "Bearer ${accessToken}" + }`); - const filteredCreatedUser = createdUser!.toObject(); + const filteredCreatedUser = createdUser.toObject(); - const userToBeReturned = omit(filteredCreatedUser, "password"); + // @ts-ignore + delete filteredCreatedUser.password; return { - user: userToBeReturned, - selectedOrganization: args.data.selectedOrgainzation, + user: filteredCreatedUser, accessToken, refreshToken, }; diff --git a/src/typeDefs/inputs.ts b/src/typeDefs/inputs.ts index a72ed4107a..e4aa13d73e 100644 --- a/src/typeDefs/inputs.ts +++ b/src/typeDefs/inputs.ts @@ -363,7 +363,7 @@ export const inputs = gql` email: EmailAddress! password: String! appLanguageCode: String - selectedOrgainzation: ID! + organizationUserBelongsToId: ID } input UserWhereInput { diff --git a/src/typeDefs/types.ts b/src/typeDefs/types.ts index b6674de48b..c58764ccbe 100644 --- a/src/typeDefs/types.ts +++ b/src/typeDefs/types.ts @@ -11,7 +11,7 @@ export const types = gql` } type AuthData { - user: UserToReturn! + user: User! accessToken: String! refreshToken: String! } @@ -456,43 +456,6 @@ export const types = gql` usersAssignedTo(input: UsersConnectionInput!): UsersConnectionResult! } - type UserToReturn { - _id: ID! - address: Address - adminApproved: Boolean - adminFor: [Organization] - appLanguageCode: String! - birthDate: Date - createdAt: DateTime! - createdEvents: [Event] - createdOrganizations: [Organization] - educationGrade: EducationGrade - email: EmailAddress! - employmentStatus: EmploymentStatus - eventAdmin: [Event] - firstName: String! - gender: Gender - image: String - joinedOrganizations: [Organization] - lastName: String! - maritalStatus: MaritalStatus - membershipRequests: [MembershipRequest] - organizationsBlockedBy: [Organization] - phone: UserPhone - pluginCreationAllowed: Boolean! - registeredEvents: [Event] - tagsAssignedWith( - after: String - before: String - first: PositiveInt - last: PositiveInt - organizationId: ID - ): UserTagsConnection - tokenVersion: Int! - updatedAt: DateTime! - userType: UserType! - } - type UsersConnectionResult { data: UsersConnection errors: [ConnectionError!]! diff --git a/src/types/generatedGraphQLTypes.ts b/src/types/generatedGraphQLTypes.ts index a9a9f0fad8..fd68a701a1 100644 --- a/src/types/generatedGraphQLTypes.ts +++ b/src/types/generatedGraphQLTypes.ts @@ -21,7 +21,7 @@ import type { InterfacePlugin as InterfacePluginModel } from '../models/Plugin'; import type { InterfacePluginField as InterfacePluginFieldModel } from '../models/PluginField'; import type { InterfacePost as InterfacePostModel } from '../models/Post'; import type { InterfaceOrganizationTagUser as InterfaceOrganizationTagUserModel } from '../models/OrganizationTagUser'; -import type { InterfaceUser as InterfaceUserModel, InterfaceUserToReturn as InterfaceUserToReturnModel } from '../models/User'; +import type { InterfaceUser as InterfaceUserModel } from '../models/User'; export type Maybe = T | null; export type InputMaybe = Maybe; export type Exact = { [K in keyof T]: T[K] }; @@ -138,7 +138,7 @@ export type AuthData = { __typename?: 'AuthData'; accessToken: Scalars['String']['output']; refreshToken: Scalars['String']['output']; - user: UserToReturn; + user: User; }; export type CheckIn = { @@ -1834,8 +1834,8 @@ export type UserInput = { email: Scalars['EmailAddress']['input']; firstName: Scalars['String']['input']; lastName: Scalars['String']['input']; + organizationUserBelongsToId?: InputMaybe; password: Scalars['String']['input']; - selectedOrgainzation: Scalars['ID']['input']; }; export type UserOrderByInput = @@ -1907,47 +1907,6 @@ export type UserTagsConnectionResult = { errors: Array; }; -export type UserToReturn = { - __typename?: 'UserToReturn'; - _id: Scalars['ID']['output']; - address?: Maybe
; - adminApproved?: Maybe; - adminFor?: Maybe>>; - appLanguageCode: Scalars['String']['output']; - birthDate?: Maybe; - createdAt: Scalars['DateTime']['output']; - createdEvents?: Maybe>>; - createdOrganizations?: Maybe>>; - educationGrade?: Maybe; - email: Scalars['EmailAddress']['output']; - employmentStatus?: Maybe; - eventAdmin?: Maybe>>; - firstName: Scalars['String']['output']; - gender?: Maybe; - image?: Maybe; - joinedOrganizations?: Maybe>>; - lastName: Scalars['String']['output']; - maritalStatus?: Maybe; - membershipRequests?: Maybe>>; - organizationsBlockedBy?: Maybe>>; - phone?: Maybe; - pluginCreationAllowed: Scalars['Boolean']['output']; - registeredEvents?: Maybe>>; - tagsAssignedWith?: Maybe; - tokenVersion: Scalars['Int']['output']; - updatedAt: Scalars['DateTime']['output']; - userType: UserType; -}; - - -export type UserToReturnTagsAssignedWithArgs = { - after?: InputMaybe; - before?: InputMaybe; - first?: InputMaybe; - last?: InputMaybe; - organizationId?: InputMaybe; -}; - export type UserType = | 'ADMIN' | 'NON_USER' @@ -2103,7 +2062,7 @@ export type ResolversTypes = { AggregatePost: ResolverTypeWrapper; AggregateUser: ResolverTypeWrapper; Any: ResolverTypeWrapper; - AuthData: ResolverTypeWrapper & { user: ResolversTypes['UserToReturn'] }>; + AuthData: ResolverTypeWrapper & { user: ResolversTypes['User'] }>; Boolean: ResolverTypeWrapper; CheckIn: ResolverTypeWrapper; CheckInInput: CheckInInput; @@ -2222,7 +2181,6 @@ export type ResolversTypes = { UserTagsConnection: ResolverTypeWrapper & { edges: Array }>; UserTagsConnectionInput: UserTagsConnectionInput; UserTagsConnectionResult: ResolverTypeWrapper & { data?: Maybe, errors: Array }>; - UserToReturn: ResolverTypeWrapper; UserType: UserType; UserWhereInput: UserWhereInput; UsersConnection: ResolverTypeWrapper & { edges: Array }>; @@ -2242,7 +2200,7 @@ export type ResolversParentTypes = { AggregatePost: AggregatePost; AggregateUser: AggregateUser; Any: Scalars['Any']['output']; - AuthData: Omit & { user: ResolversParentTypes['UserToReturn'] }; + AuthData: Omit & { user: ResolversParentTypes['User'] }; Boolean: Scalars['Boolean']['output']; CheckIn: InterfaceCheckInModel; CheckInInput: CheckInInput; @@ -2349,7 +2307,6 @@ export type ResolversParentTypes = { UserTagsConnection: Omit & { edges: Array }; UserTagsConnectionInput: UserTagsConnectionInput; UserTagsConnectionResult: Omit & { data?: Maybe, errors: Array }; - UserToReturn: InterfaceUserToReturnModel; UserWhereInput: UserWhereInput; UsersConnection: Omit & { edges: Array }; UsersConnectionInput: UsersConnectionInput; @@ -2440,7 +2397,7 @@ export interface AnyScalarConfig extends GraphQLScalarTypeConfig = { accessToken?: Resolver; refreshToken?: Resolver; - user?: Resolver; + user?: Resolver; __isTypeOf?: IsTypeOfResolverFn; }; @@ -3096,38 +3053,6 @@ export type UserTagsConnectionResultResolvers; }; -export type UserToReturnResolvers = { - _id?: Resolver; - address?: Resolver, ParentType, ContextType>; - adminApproved?: Resolver, ParentType, ContextType>; - adminFor?: Resolver>>, ParentType, ContextType>; - appLanguageCode?: Resolver; - birthDate?: Resolver, ParentType, ContextType>; - createdAt?: Resolver; - createdEvents?: Resolver>>, ParentType, ContextType>; - createdOrganizations?: Resolver>>, ParentType, ContextType>; - educationGrade?: Resolver, ParentType, ContextType>; - email?: Resolver; - employmentStatus?: Resolver, ParentType, ContextType>; - eventAdmin?: Resolver>>, ParentType, ContextType>; - firstName?: Resolver; - gender?: Resolver, ParentType, ContextType>; - image?: Resolver, ParentType, ContextType>; - joinedOrganizations?: Resolver>>, ParentType, ContextType>; - lastName?: Resolver; - maritalStatus?: Resolver, ParentType, ContextType>; - membershipRequests?: Resolver>>, ParentType, ContextType>; - organizationsBlockedBy?: Resolver>>, ParentType, ContextType>; - phone?: Resolver, ParentType, ContextType>; - pluginCreationAllowed?: Resolver; - registeredEvents?: Resolver>>, ParentType, ContextType>; - tagsAssignedWith?: Resolver, ParentType, ContextType, Partial>; - tokenVersion?: Resolver; - updatedAt?: Resolver; - userType?: Resolver; - __isTypeOf?: IsTypeOfResolverFn; -}; - export type UsersConnectionResolvers = { edges?: Resolver, ParentType, ContextType>; pageInfo?: Resolver; @@ -3213,7 +3138,6 @@ export type Resolvers = { UserTagEdge?: UserTagEdgeResolvers; UserTagsConnection?: UserTagsConnectionResolvers; UserTagsConnectionResult?: UserTagsConnectionResultResolvers; - UserToReturn?: UserToReturnResolvers; UsersConnection?: UsersConnectionResolvers; UsersConnectionResult?: UsersConnectionResultResolvers; }; diff --git a/src/utilities/loadDefaultOrganization.ts b/src/utilities/loadDefaultOrganization.ts deleted file mode 100644 index 652065032d..0000000000 --- a/src/utilities/loadDefaultOrganization.ts +++ /dev/null @@ -1,82 +0,0 @@ -import mongoose from "mongoose"; -import path from "path"; -import { Organization, Post, User, Event } from "../models"; -import fs from "fs"; -import dotenv from "dotenv"; -import yargs from "yargs"; - -interface InterfaceArgs { - items?: string; - format?: boolean; - _: unknown; -} - -export async function formatDatabase(): Promise { - await Promise.all([ - User.deleteMany({}), - Organization.deleteMany({}), - Event.deleteMany({}), - Post.deleteMany({}), - ]); - console.log("Cleared all collections\n"); -} - -dotenv.config(); -/** - * The function which loads the default organization, so that there is always altleast 1 organization in the DB - * @returns a Promise that resolves to void - */ - -export async function loadDefaultOrganization(): Promise { - let session!: mongoose.ClientSession; - const url = process.env.MONGO_DB_URL; - if (url == null) { - console.log("Couldn't find mongodb url"); - return; - } - await mongoose.connect(url, { - useCreateIndex: true, - useUnifiedTopology: true, - useFindAndModify: false, - useNewUrlParser: true, - }); - const { format } = yargs - .options({ - items: { - alias: "i", - describe: - "Comma-separated list of collections to load sample data into", - type: "string", - }, - format: { - alias: "f", - describe: - "Formats all the collections present in the database before the insertion of objects. [WARNING] Use carefully.", - type: "boolean", - }, - }) - .parseSync() as InterfaceArgs; - - // Check if specific collections need to be inserted - if (format) { - await formatDatabase(); - } - session = await mongoose.startSession(); - const userData = await fs.readFileSync( - path.join(__dirname, `../../sample_data/defaultOrganizationAdmin.json`), - "utf8" - ); - const userDocs = JSON.parse(userData) as Record[]; - await User.insertMany(userDocs); - const data = await fs.readFileSync( - path.join(__dirname, `../../sample_data/defaultOrganization.json`), - "utf8" - ); - const docs = JSON.parse(data) as Record[]; - await Organization.insertMany(docs); - console.log("Default Organization loaded"); - session?.endSession(); - await mongoose.connection.close(); -} - -loadDefaultOrganization(); diff --git a/tests/helpers/membershipRequests.ts b/tests/helpers/membershipRequests.ts index 7261de32d9..05a4f4fbf8 100644 --- a/tests/helpers/membershipRequests.ts +++ b/tests/helpers/membershipRequests.ts @@ -10,10 +10,10 @@ export type TestMembershipRequestType = Document) | null; -export const createTestMembershipRequest = async ( - givenUser?: TestUserType -): Promise<[TestUserType, TestOrganizationType, TestMembershipRequestType]> => { - const testUser = givenUser == null ? await createTestUser() : givenUser; +export const createTestMembershipRequest = async (): Promise< + [TestUserType, TestOrganizationType, TestMembershipRequestType] +> => { + const testUser = await createTestUser(); if (testUser) { const testOrganization = await Organization.create({ diff --git a/tests/helpers/userAndOrg.ts b/tests/helpers/userAndOrg.ts index 1952130283..d3e7c11f73 100644 --- a/tests/helpers/userAndOrg.ts +++ b/tests/helpers/userAndOrg.ts @@ -24,19 +24,6 @@ export const createTestUser = async (): Promise => { return testUser; }; -export const createAdminApprovedTestUser = async (): Promise => { - const testUser = await User.create({ - email: `email${nanoid().toLowerCase()}@gmail.com`, - password: `pass${nanoid().toLowerCase()}`, - firstName: `firstName${nanoid().toLowerCase()}`, - lastName: `lastName${nanoid().toLowerCase()}`, - image: null, - appLanguageCode: "en", - adminApproved: true, - }); - return testUser; -}; - export const createTestOrganizationWithAdmin = async ( userID: string, isMember = true, diff --git a/tests/resolvers/Mutation/acceptMembershipRequest.spec.ts b/tests/resolvers/Mutation/acceptMembershipRequest.spec.ts index 16f38f799c..f7a9612f81 100644 --- a/tests/resolvers/Mutation/acceptMembershipRequest.spec.ts +++ b/tests/resolvers/Mutation/acceptMembershipRequest.spec.ts @@ -21,10 +21,9 @@ import { vi, afterEach, } from "vitest"; -import { - type TestUserType, - type TestOrganizationType, - createAdminApprovedTestUser, +import type { + TestUserType, + TestOrganizationType, } from "../../helpers/userAndOrg"; import type { TestMembershipRequestType } from "../../helpers/membershipRequests"; import { createTestMembershipRequest } from "../../helpers/membershipRequests"; @@ -249,7 +248,7 @@ describe("resolvers -> Mutation -> acceptMembershipRequest", () => { } }); - it(`accepts the membershipRequest for a newly created member and returns it`, async () => { + it(`accepts the membershipRequest and returns it`, async () => { await Organization.updateOne( { _id: testOrganization?._id, @@ -293,7 +292,7 @@ describe("resolvers -> Mutation -> acceptMembershipRequest", () => { const updatedTestUser = await User.findOne({ _id: testUser?._id, }) - .select(["joinedOrganizations", "membershipRequests", "adminApproved"]) + .select(["joinedOrganizations", "membershipRequests"]) .lean(); expect(updatedTestUser).toEqual( @@ -302,60 +301,5 @@ describe("resolvers -> Mutation -> acceptMembershipRequest", () => { membershipRequests: expect.arrayContaining([]), }) ); - expect(updatedTestUser?.adminApproved).toBe(true); - }); - it(`accepts the membershipRequest for already existing member and returns it`, async () => { - const testUser = await createAdminApprovedTestUser(); - const localTestData = await createTestMembershipRequest(testUser); - await Organization.updateOne( - { - _id: localTestData[1]?._id, - }, - { - $set: { - members: [], - }, - } - ); - - const args: MutationAcceptMembershipRequestArgs = { - membershipRequestId: localTestData[2]?.id, - }; - - const context = { - userId: localTestData[0]?.id, - }; - const { acceptMembershipRequest: acceptMembershipRequestResolver } = - await import("../../../src/resolvers/Mutation/acceptMembershipRequest"); - const acceptMembershipRequestPayload = - await acceptMembershipRequestResolver?.({}, args, context); - - expect(String(acceptMembershipRequestPayload?._id)).toBe( - String(localTestData[2]?.id) - ); - - const updatedTestOrganization = await Organization.findOne({ - _id: localTestData[1]?.id, - }) - .select(["members", "membershipRequests"]) - .lean(); - expect(updatedTestOrganization?.members.length).toBe(1); - expect(String(updatedTestOrganization?.members[0])).toEqual( - String(localTestData[0]?.id) - ); - expect(updatedTestOrganization?.membershipRequests.length).toEqual(0); - - const updatedTestUser = await User.findOne({ - _id: localTestData[0]?.id, - }) - .select(["joinedOrganizations", "membershipRequests", "adminApproved"]) - .lean(); - - expect(updatedTestUser).toEqual( - expect.objectContaining({ - joinedOrganizations: expect.arrayContaining([localTestData[1]?._id]), - membershipRequests: expect.arrayContaining([]), - }) - ); }); }); diff --git a/tests/resolvers/Mutation/signUp.spec.ts b/tests/resolvers/Mutation/signUp.spec.ts index 2179f1a5a6..68223ee345 100644 --- a/tests/resolvers/Mutation/signUp.spec.ts +++ b/tests/resolvers/Mutation/signUp.spec.ts @@ -1,8 +1,7 @@ import "dotenv/config"; -import bcrypt from "bcryptjs"; import type mongoose from "mongoose"; import { Types } from "mongoose"; -import { Organization, User } from "../../../src/models"; +import { User } from "../../../src/models"; import type { MutationSignUpArgs } from "../../../src/types/generatedGraphQLTypes"; import { connect, disconnect } from "../../helpers/db"; import { @@ -61,7 +60,7 @@ describe("resolvers -> Mutation -> signUp", () => { vi.restoreAllMocks(); }); - it(`creates the user and returns the created with adminAprooved=true, accessToken and refreshToken when organization doesn't require user registration`, async () => { + it(`creates the user and returns the created user with accessToken, refreshToken`, async () => { const email = `email${nanoid().toLowerCase()}@gmail.com`; const args: MutationSignUpArgs = { @@ -71,7 +70,7 @@ describe("resolvers -> Mutation -> signUp", () => { lastName: "lastName", password: "password", appLanguageCode: "en", - selectedOrgainzation: testOrganization?._id.toString(), + organizationUserBelongsToId: undefined, }, }; const { signUp: signUpResolver } = await import( @@ -92,12 +91,6 @@ describe("resolvers -> Mutation -> signUp", () => { user: createdUser, }); - const updatedOrganization = await Organization.findById( - testOrganization?._id - ).select("members"); - expect(updatedOrganization?.members.includes(testUser?._id)).toBe(true); - expect(createdUser?.adminApproved).toBe(true); - expect(typeof signUpPayload?.accessToken).toEqual("string"); expect(signUpPayload?.accessToken.length).toBeGreaterThan(1); @@ -105,13 +98,10 @@ describe("resolvers -> Mutation -> signUp", () => { expect(signUpPayload?.refreshToken.length).toBeGreaterThan(1); }); - it(`creates the user and returns the created with a membership request, adminAprooved=false, accessToken and refreshToken when organization require user registration`, async () => { + it(`creates the user with provided organizationUserBelongsToId and returns the + created user with accessToken, refreshToken`, async () => { const email = `email${nanoid().toLowerCase()}@gmail.com`; - const localTestOrganization = await createTestUserAndOrganization( - true, - true, - true - ); + const args: MutationSignUpArgs = { data: { email, @@ -119,7 +109,7 @@ describe("resolvers -> Mutation -> signUp", () => { lastName: "lastName", password: "password", appLanguageCode: "en", - selectedOrgainzation: localTestOrganization[1]?.id, + organizationUserBelongsToId: testOrganization?.id, }, }; const { signUp: signUpResolver } = await import( @@ -133,22 +123,13 @@ describe("resolvers -> Mutation -> signUp", () => { }) .select("-password") .lean(); + expect({ user: signUpPayload?.user, }).toEqual({ user: createdUser, }); - const password = await User.findOne({ - email, - }) - .select("password") - .lean(); - const ifRightPassword = await bcrypt.compare( - args.data.password, - password?.password! - ); - expect(ifRightPassword).toBe(true); - expect(createdUser?.adminApproved).toBe(false); + expect(typeof signUpPayload?.accessToken).toEqual("string"); expect(signUpPayload?.accessToken.length).toBeGreaterThan(1); @@ -169,7 +150,7 @@ describe("resolvers -> Mutation -> signUp", () => { lastName: "lastName", password: "password", appLanguageCode: "en", - selectedOrgainzation: testOrganization?.id, + organizationUserBelongsToId: testOrganization?.id, }, file: testImagePath, }; @@ -195,7 +176,7 @@ describe("resolvers -> Mutation -> signUp", () => { lastName: "lastName", password: "password", appLanguageCode: "en", - selectedOrgainzation: testOrganization?.id, + organizationUserBelongsToId: undefined, }, }; const { signUp: signUpResolver } = await import( @@ -209,11 +190,6 @@ describe("resolvers -> Mutation -> signUp", () => { expect(createdUser?.adminApproved).toBeTruthy(); }); it(`Check if the User is not being promoted to SUPER ADMIN automatically`, async () => { - const localTestOrganization = await createTestUserAndOrganization( - true, - true, - true - ); const email = `email${nanoid().toLowerCase()}@gmail.com`; const args: MutationSignUpArgs = { data: { @@ -222,7 +198,7 @@ describe("resolvers -> Mutation -> signUp", () => { lastName: "lastName", password: "password", appLanguageCode: "en", - selectedOrgainzation: localTestOrganization[1]?.id, + organizationUserBelongsToId: undefined, }, }; const { signUp: signUpResolver } = await import( @@ -257,7 +233,7 @@ describe("resolvers -> Mutation -> signUp", () => { lastName: "lastName", password: "password", appLanguageCode: "en", - selectedOrgainzation: testOrganization?.id, + organizationUserBelongsToId: undefined, }, }; @@ -286,7 +262,7 @@ describe("resolvers -> Mutation -> signUp", () => { lastName: "lastName", password: "password", appLanguageCode: "en", - selectedOrgainzation: Types.ObjectId().toString(), + organizationUserBelongsToId: Types.ObjectId().toString(), }, };