示例#1
0
        public IHttpActionResult LogoutFromApp()
        {
            string token = ControllerHelper.GetTokenFromAuthorizationHeader(Request.Headers);

            if (token == null)
            {
                return(Unauthorized());
            }
            try
            {
                using (var dbContext = new BroadwayBuilderContext())
                {
                    dbContext.Sessions.Remove(dbContext.Sessions
                                              .Where(session => session.Token == token).First());
                    dbContext.SaveChanges();
                    return(Ok("User has successfully logged out."));
                }
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
示例#2
0
        public IHttpActionResult DowngradeUser([FromUri] int userId)
        {
            var token = ControllerHelper.GetTokenFromAuthorizationHeader(Request.Headers);

            try
            {
                using (var dbcontext = new BroadwayBuilderContext())
                {
                    var authorizationService = new AuthorizationService(dbcontext);

                    var userService = new UserService(dbcontext);

                    var requestingUser = userService.GetUserByToken(token);

                    var isAuthorized = authorizationService.HasPermission(requestingUser, DataAccessLayer.Enums.PermissionsEnum.DowngradeTheaterAdminToGeneralUser);

                    if (!isAuthorized)
                    {
                        return(Unauthorized());
                    }

                    var isTheaterAdmin = userService.HasUserRole(userId, DataAccessLayer.Enums.RoleEnum.TheaterAdmin);

                    if (isTheaterAdmin)
                    {
                        userService.RemoveUserRole(userId, DataAccessLayer.Enums.RoleEnum.TheaterAdmin);
                        dbcontext.SaveChanges();
                    }

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
示例#3
0
        public IHttpActionResult LoginFromSSO([FromBody] LoginRequestModel request)
        {
            using (var _dbcontext = new BroadwayBuilderContext())
            {
                try
                {
                    ControllerHelper.ValidateLoginRequestModel(ModelState, request);

                    Guid userSsoId = ControllerHelper.ParseAndCheckId(request.SSOUserId);

                    SignatureService signatureService = new SignatureService();
                    // Check if the signature is invalid
                    if (!signatureService.IsValidClientRequest(request.SSOUserId, request.Email, request.Timestamp, request.Signature))
                    {
                        return(Content(HttpStatusCode.Unauthorized, "Invalid Signature Token"));
                    }

                    // Now we have to get a user (check if it exists)
                    UserService userService = new UserService(_dbcontext);

                    User user;
                    try
                    {
                        user = userService.GetUser(request.Email);
                    }
                    catch (UserNotFoundException ex)
                    {
                        var newUser = new User()
                        {
                            UserGuid    = userSsoId,
                            Username    = request.Email,
                            DateCreated = DateTime.UtcNow,
                            IsEnabled   = false,
                            IsComplete  = false
                        };
                        userService.CreateUser(newUser);
                        user = newUser;

                        // Everyone starts off as a general user
                        userService.AddUserRole(user.UserId, DataAccessLayer.Enums.RoleEnum.GeneralUser);
                    }

                    // User was found, so login user
                    Session session = new Session()
                    {
                        UserId    = user.UserId,
                        Token     = Guid.NewGuid().ToString(),
                        Signature = request.Signature,
                        CreatedAt = DateTime.UtcNow,
                        ExpiresAt = DateTime.UtcNow.AddMinutes(30),
                        UpdatedAt = DateTime.UtcNow,
                        Id        = Guid.NewGuid(),
                    };

                    _dbcontext.Sessions.Add(session);
                    _dbcontext.SaveChanges();
                    //Logging Usage
                    //TODO: possibly change the userid argument for LogUsage
                    LoggerHelper.LogUsage("Login", user.UserId);
                    var redirectURL = $"https://ui.broadwaybuilder.xyz/#/login?token={session.Token}";
                    return(Redirect(redirectURL));
                }
                catch (Exception e)
                {
                    return(InternalServerError(e));
                    //TODO: LogError
                }
            }
        }
示例#4
0
        public IHttpActionResult UploadUserResume()
        {
            string token = ControllerHelper.GetTokenFromAuthorizationHeader(Request.Headers);

            if (token == null)
            {
                return(Unauthorized());
            }
            //A list in case we want to accept more than one file type
            List <string> allowedFileExtension = new List <string> {
                ".pdf"
            };
            //Business Rule - only one file allowed to submit
            int maxFileCount = 1;
            // Max file size is 1MB
            const int maxContentLength = 1024 * 1024 * 1;

            try
            {
                //get the content, headers, etc the full request of the current http request
                var httpRequest   = HttpContext.Current.Request;
                var fileValidator = new FileValidator();
                //Validate the submitted file to verify that it complies with Business Rules
                var validationResult = fileValidator.ValidateFiles(httpRequest.Files, allowedFileExtension, maxContentLength, maxFileCount);
                if (!validationResult.ValidationSuccessful)//if one or more business rules were violated
                {
                    var errorMessage = string.Join("\n", validationResult.Reasons);
                    return(Content((HttpStatusCode)406, errorMessage));
                }
                // Grab current file of the request
                var postedFile = httpRequest.Files[0];
                using (var dbContext = new BroadwayBuilderContext())
                {
                    var userService = new UserService(dbContext);
                    var user        = userService.GetUserByToken(token);
                    if (user == null)//check if user exists
                    {
                        return(Content((HttpStatusCode)404, "User does not exist"));
                    }
                    var    resumeService = new ResumeService(dbContext);
                    Resume resume        = resumeService.GetResumeByUserID(user.UserId);
                    if (resume == null)//check if user has already submitted a resume
                    {
                        Resume userResume = new Resume(user.UserId, Guid.NewGuid());
                        resumeService.CreateResume(userResume);
                        var result = dbContext.SaveChanges();
                        if (result <= 0)
                        {
                            return(Content((HttpStatusCode)500, "Failed to add a resume onto our database"));
                        }
                        resume = userResume;
                    }
                    //Folder path of the user
                    var subdir = Path.Combine(ConfigurationManager.AppSettings["ResumeDir"], (resume.ResumeGuid.ToString() + "/")); //@"C:\Resumes\"+resume.ResumeGuid;
                    //Filepath of the submitted file
                    var filePath = Path.Combine(subdir, resume.ResumeGuid.ToString() + ".pdf");                                     // subdir+@"\"+resume.ResumeGuid+".pdf";

                    if (!Directory.Exists(subdir))                                                                                  //check if the directory exists
                    {
                        Directory.CreateDirectory(subdir);                                                                          //create the directory if it doesnt exist
                    }
                    //saves file onto the specified file path and overwrites any file that may exist in that shares the same path
                    postedFile.SaveAs(filePath);
                    LoggerHelper.LogUsage("Upload Resume", user.UserId);
                    return(Content((HttpStatusCode)200, "File Uploaded"));
                }
            }
            catch (HttpException e)//HttpPostedFile.SaveAs exception
            {
                return(Content((HttpStatusCode)500, "Unable to save the file onto our file system."));
            }
            catch (IOException e)//Exception thrown when creating directory
            {
                return(Content((HttpStatusCode)500, "Unable to delete the job posting"));
            }
            catch (DbUpdateException e)//exception thrown while saving the database
            {
                return(Content((HttpStatusCode)500, "Unable to delete the job posting"));
            }
            catch (DbEntityValidationException dbEntityValidationException)
            {
                return(Content((HttpStatusCode)500, "Unable to delete the job posting"));
            }
            catch (Exception e)
            {
                return(Content((HttpStatusCode)400, e.Message));
            }
        }