예제 #1
0
        public async Task <IActionResult> CreateOrganisation(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Organisation/CreateOrganisation")] HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function(CreateOrganisation) processed a request.");

            try
            {
                var accessTokenResult = _tokenProvider.ValidateToken(req);

                if (accessTokenResult.Status == AccessTokenStatus.Valid)
                {
                    Guid userAccountId = new Guid(accessTokenResult.Principal.Claims.First(c => c.Type == "UserAccount").Value);
                    log.LogInformation($"JWT validated for UserAccount: {userAccountId}.");

                    string requestBody             = await new StreamReader(req.Body).ReadToEndAsync();
                    var    organisationCreateModel = JsonConvert.DeserializeObject <OrganisationCreateModel>(requestBody);

                    var organisation = new Organisation()
                    {
                        OrganisationName = organisationCreateModel.OrganisationName,
                        CreatedById      = userAccountId
                    };

                    var organisationRepo = new OrganisationRepository();
                    var organisationId   = organisationRepo.CreateOrganisation(organisation);

                    var organisationMembership = new OrganisationMembership()
                    {
                        OrganisationId       = organisationId,
                        UserAccountId        = userAccountId,
                        UserType             = UserType.OrganisationOwner,
                        OrganisationInviteId = null
                    };

                    // store the OrganisationMembership
                    var organisationMembershipRepo = new OrganisationMembershipRepository();
                    organisationMembershipRepo.CreateOrganisationMembership(organisationMembership);

                    // create JWT with the OrganisationId as
                    var jwt = _tokenCreator.CreateToken(userAccountId, organisationId);
                    return(new OkObjectResult(jwt));
                }
                else
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception exception)
            {
                return(new BadRequestObjectResult(exception.Message));
            }
        }