示例#1
0
        public ReturnModel CreateBoard([FromBody] AccountBoardsModel model, long idOrganization, string accesToken)
        {
            var         account = _readOnlyRepository.First <Account>(account1 => account1.Token == accesToken);
            ReturnModel remodel = new ReturnModel();

            if (account != null)
            {
                if (account.VerifyToken(account))
                {
                    Organization organization = _readOnlyRepository.GetById <Organization>(idOrganization);
                    Board        board        = _mappingEngine.Map <AccountBoardsModel, Board>(model);
                    board.Administrator = account;
                    Board boardCreated = _writeOnlyRepository.Create(board);
                    if (boardCreated != null)
                    {
                        organization.AddBoard(boardCreated);
                        Activity activity = new Activity();
                        activity.Text = account.FirstName + " Creo un board";
                        account.AddActivities(activity);
                        var organizacionUpdate = _writeOnlyRepository.Update(organization);
                        var accountUpdate      = _writeOnlyRepository.Update(account);
                        return(remodel.ConfigureModel("Succesfull", "Se creo el board correctamente", remodel));
                    }
                    return(remodel.ConfigureModel("Error", "No se pudo crear el board", remodel));
                }
                return(remodel.ConfigureModel("Error", "Su session ya expiro", remodel));
            }
            return(remodel.ConfigureModel("Error", "No se pudo acceder a su cuenta", remodel));
        }
示例#2
0
        public ReturnModel Register([FromBody] OrganizationModel model, string accesToken)
        {
            var account =
                _readOnlyRepository.First <Account>(
                    account1 => account1.Token == accesToken);
            ReturnModel remodel = new ReturnModel();

            if (account != null)
            {
                if (account.VerifyToken(account))
                {
                    Organization organization        = _mappingEngine.Map <OrganizationModel, Organization>(model);
                    Organization organizationCreated = _writeOnlyRepository.Create(organization);
                    if (organizationCreated != null)
                    {
                        account.AddOrganization(organizationCreated);
                        Activity activity = new Activity();
                        activity.Text = account.FirstName + " Creo una organizacion";
                        account.AddActivities(activity);
                        var accountUpdate = _writeOnlyRepository.Update(account);

                        return(remodel.ConfigureModel("SuccessFull", "Se Creo satisfactoriamente la organizacion " + organizationCreated.Title, remodel));;
                    }
                }
                return(remodel.ConfigureModel("Error", "Su session ya expiro", remodel));
            }
            return(remodel.ConfigureModel("Error", "No se pudo acceder a su cuenta", remodel));
        }
        public new ActionResult Profile()
        {
            //long userId = Convert.ToInt64(Session["userId"]);
            var userData = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name);

            return(View(Mapper.Map <AccountProfileModel>(userData)));
        }
示例#4
0
        public ReturnModel CreateCard([FromBody] CardModel model, long idLine, string accesToken)
        {
            var account =
                _readOnlyRepository.First <Account>(
                    account1 => account1.Token == accesToken);

            ReturnModel remodel = new ReturnModel();

            if (account != null)
            {
                if (account.VerifyToken(account))
                {
                    Lines line        = _readOnlyRepository.GetById <Lines>(idLine);
                    Cards card        = _mappingEngine.Map <CardModel, Cards>(model);
                    Cards cardCreated = _writeOnlyRepository.Create(card);
                    if (cardCreated != null)
                    {
                        line.AddCard(cardCreated);
                        var      lineUpdate = _writeOnlyRepository.Update(line);
                        Activity activity   = new Activity();
                        activity.Text = account.FirstName + " Creo una card en " + line.Title;
                        account.AddActivities(activity);
                        var accountUpdate = _writeOnlyRepository.Update(account);
                        return(remodel.ConfigureModel("Successfull", "Se creo correctamente la card " + cardCreated.Text, remodel));
                    }
                    return(remodel.ConfigureModel("Error", "No se pudo crear la card", remodel));
                }
                return(remodel.ConfigureModel("Error", "Su session ya expiro", remodel));
            }
            return(remodel.ConfigureModel("Error", "No se pudo acceder a la cuenta", remodel));
        }
        public ReturnModel Login([FromBody] AccountLoginModel model)
        {
            var account =
                _readOnlyRepository.First <Account>(
                    account1 => account1.Email == model.Email && account1.Password == Encrypt(model.Password));

            ReturnModel remodel = new ReturnModel();

            if (account != null)
            {
                //account.TokenTime = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
                account.TokenTime = DateTime.Now;
                account.Token     = Guid.NewGuid().ToString();
                //account.Token = Convert.ToBase64String(account.TokenTime.Concat(account.TokenKey).ToArray()).Replace("/", "A").Replace("+", "B"); //.Replace(@"/", "").Replace(@"+","")

                var tokenCreated = _writeOnlyRepository.Update(account);
                if (tokenCreated != null)
                {
                    return new AuthenticationModel()
                           {
                               Token = account.Token
                           }
                }
                ;
            }
            return(remodel.ConfigureModel("Error", "NO se pudo acceder a su cuenta", remodel));
        }
        public ActionResult ReferralInvite(ReferralInviteModel model)
        {
            var userData = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name);

            var emailBody = new StringBuilder("<b>Your friend </b>");

            emailBody.Append("<b>" + userData.Name + " " + userData.LastName + "</b>");
            emailBody.Append("<b> wants you to join to MiniDropBox, a site where you can store your files in the cloud!!</b>");
            emailBody.Append("<br/>");
            emailBody.Append("<b>To register in the site just click on the link below and fill up a quick form! Enjoy!!! </b>");

            //emailBody.Append("http://minidropbox-1.apphb.com/AccountSignUp/AccountSignUp?token=" + userId);
            emailBody.Append("http://localhost:1840/AccountSignUp/AccountSignUp?token=" + userData.Id);
            emailBody.Append("<br/>");
            emailBody.Append("<br/>");
            emailBody.Append("<br/>");

            if (MailSender.SendEmail(model.ReferalEmail, "Join Mini DropBox", emailBody.ToString()))
            {
                AddActivity("Se ha mandado una invitacion a " + model.ReferalEmail);
                Success("E-Mail sent successfully!!");
                return(View(model));
            }
            Error("E-Mail couldn't be sent!!!!");
            return(View(model));
        }
        public ReturnModel CreateLine([FromBody] LineModel model, long idBoard, string accesToken)
        {
            var account = _readOnlyRepository.First <Account>(account1 => account1.Token == accesToken);

            ReturnModel remodel = new ReturnModel();

            if (account != null)
            {
                if (account.VerifyToken(account))
                {
                    Board board       = _readOnlyRepository.GetById <Board>(idBoard);
                    Lines line        = _mappingEngine.Map <LineModel, Lines>(model);
                    Lines lineCreated = _writeOnlyRepository.Create(line);
                    if (lineCreated != null)
                    {
                        board.AddLine(lineCreated);
                        var      boardUpdate = _writeOnlyRepository.Update(board);
                        Activity activity    = new Activity();
                        activity.Text = account.FirstName + " Creo una Line en " + board.Title;
                        account.AddActivities(activity);
                        var accountUpdate = _writeOnlyRepository.Update(account);
                        return(remodel.ConfigureModel("Successfull", "Se creo exitosamente la line " + lineCreated.Title, remodel));
                    }
                    return(remodel.ConfigureModel("Error", "No se pudo crear la line", remodel));
                }
                return(remodel.ConfigureModel("Error", "Su session ya expiro", remodel));
            }
            return(remodel.ConfigureModel("Error", "No se pudo acceder a su cuenta", remodel));
        }
        public AuthenticationModel Login([FromBody] AccountLoginModel model)
        {
            //var account = _readOnlyRepository.First<Account>(account1 => account1.Email == model.Email
            //   && BCrypt.Net.BCrypt.Verify(model.Password, account1.Password));

            var account = _readOnlyRepository.First <Account>(account1 => account1.Email == model.Email &&
                                                              account1.Password == model.Password);

            if (account != null)
            {
                var session        = AccountHelpers.CreateNewSession(account);
                var sessionCreated = _writeOnlyRepository.Create(session);
                if (sessionCreated != null)
                {
                    return new AuthenticationModel()
                           {
                               Token = session.Token,
                               YourSessionExpireIn = session.Duration
                           }
                }
                ;
            }

            throw new BadRequestException("User or Password is incorrect");
        }
示例#9
0
        public SuccessfulMessageResponse CreateOrganization([FromBody] OrganizationCreationModel model, string token)
        {
            var session = IsTokenExpired(token);
            var account = _readOnlyRepository.First <Account>(account1 => account1.Id == session.User.Id);

            AccountHelpers.CreateOrganizationDefault(account, model.Title, model.Description);
            return(new SuccessfulMessageResponse("Organization has been created"));
        }
示例#10
0
        public ActionResult Delete(int Id)
        {
            var emp = _readOnlyRepository.First <Departamento>(x => x.Id == Id);

            _writeOnlyRepository.Archive(emp);
            Success("Eliminado correctamente");
            return(RedirectToAction("Index"));
        }
示例#11
0
        public void AddActivity(string actividad)
        {
            var account = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name);
            var act     = new Actividades();

            act.Actividad = actividad;
            act.hora      = DateTime.Now;
            account.History.Add(act);
            _writeOnlyRepository.Update(account);
        }
示例#12
0
        public ActionResult LogIn(AccountLoginModel model)
        {
            var passwordEncripted = EncriptacionMD5.Encriptar(model.Password);
            var result            = _readOnlyRepository.First <Account>(x => x.EMail == model.EMail && x.Password == passwordEncripted);

            if (result != null)
            {
                if (!CheckPassword(result, passwordEncripted))
                {
                    Error("Contraseña invalida");
                    return(View());
                }
                if (result.IsBlocked)
                {
                    Error(
                        "Your account has been blocked by the Admin due to violation of the terms of usage of this site!");
                    return(View());
                }



                if (!result.Isconfirmed)
                {
                    Error(
                        "Your account has not been confirmed!");
                    return(View());
                }
                if (result.IsArchived)
                {
                    Error("Your account is inactive, to activate it again send an e-mail to [email protected]");
                    return(View());
                }

                var roles = result.IsAdmin
                    ? new List <string>(new[] { "Admin" })
                    : new List <string>(new[] { "User" });

                FormsAuthentication.SetAuthCookie(model.EMail, model.RememberMe);
                SetAuthenticationCookie(model.EMail, roles);


                if (result.IsAdmin)
                {
                    return(RedirectToAction("RegisteredUsersList", "RegisteredUsersList"));
                }

                Session["ActualPath"]   = string.Empty;
                Session["ActualFolder"] = string.Empty;
                return(RedirectToAction("ListAllContent", "Disk"));
            }


            Error("E-Mail or Password is incorrect!!!");
            return(View());
        }
        bool Bitacora(string activida)
        {
            var usuario = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name);
            var pasos   = new Actividades();

            pasos.Actividad = activida;
            pasos.hora      = DateTime.Now;
            usuario.History.Add(pasos);
            usuario = _writeOnlyRepository.Update(usuario);
            return(true);
        }
示例#14
0
        private bool checkCredenciales(string userName, string password)
        {
            var account = _readOnlyRepository.First <Account>(x => x.EMail == userName);

            if (checkCuenta(account))
            {
                if (account.Password == EncriptacionMD5.Encriptar(password))
                {
                    return(true);
                }
            }
            return(false);
        }
示例#15
0
        public LoginModule(IPasswordEncryptor passwordEncryptor, IReadOnlyRepository readOnlyRepository,
            IUserSessionFactory userSessionFactory)
        {
            Post["/login"] =
                _ =>
                {
                    var loginInfo = this.Bind<LoginRequest>();
                    if (loginInfo.Email == null) throw new UserInputPropertyMissingException("Email");
                    if (loginInfo.Password == null) throw new UserInputPropertyMissingException("Password");

                    EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password);

                    try
                    {
                        var user =
                            readOnlyRepository.First<User>(
                                x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password);

                        UserLoginSession userLoginSession = userSessionFactory.Create(user);

                        return new SuccessfulLoginResponse<Guid>(userLoginSession.Id, user.Id, user.Name,
                            userLoginSession.Expires);
                    }
                    catch (ItemNotFoundException<User>)
                    {
                        throw new UnauthorizedAccessException();
                    }
                };
        }
示例#16
0
        public UserModule(IMappingEngine mappingEngine, IReadOnlyRepository readOnlyRepository)
        {
            Get["/me"] = r => mappingEngine.Map<User, MeResponse>(this.UserSession().User);

            Get["/user/exists"] =
                r =>
                    {
                        bool exists = false;
                        bool activated = false;
                        var email = (string) Request.Query.email;
                        try
                        {
                            var user =
                                readOnlyRepository.First<User>(x => x.Email == email);
                            exists = true;
                            activated = user.Activated;
                        }
                        catch (ItemNotFoundException<User>)
                        {
                        }
                        return new UserExistenceResponse
                                   {
                                       Exists = exists,
                                       Activated = activated,
                                   };
                    };
        }
示例#17
0
        public ActionResult PasswordRecovery(PasswordRecoveryModel model)
        {
            var result = _readOnlyRepository.First <Account>(a => a.EMail == model.EMailAddress);

            if (result != null)
            {
                var fechaActual = DateTime.Now.Date;

                var pass  = result.Password;
                var data  = "" + fechaActual.Day + fechaActual.Month + fechaActual.Year;
                var token = pass + ";" + EncriptacionMD5.Encriptar(data);

                //var url = "http://Galeria-1.apphb.com/PasswordReset/PasswordReset";
                var url = "http://Galeriaclase.apphb.com/PasswordReset/PasswordReset";

                var emailBody = new StringBuilder("<b>Go to the following link to change your password: </b>");
                emailBody.Append("<br/>");
                emailBody.Append("<br/>");
                emailBody.Append("<b>" + url + "?token=" + token + "<b>");
                emailBody.Append("<br/>");
                emailBody.Append("<br/>");
                emailBody.Append("<b>This link is only valid through " + fechaActual.Day + "/" + fechaActual.Month + "/" + fechaActual.Year + "</b>");

                if (MailSender.SendEmail(model.EMailAddress, "Password Recovery", emailBody.ToString()))
                {
                    return(Cancel());
                }

                Error("E-Mail failed to be sent, please try again!!!");
                return(View(model));
            }

            Error("E-Mail address is not registered in this site!!!");
            return(View(model));
        }
示例#18
0
        public void Validate(IUserSession userSession, CreatePasswordResetToken command)
        {
            var validationFailures = new List <ValidationFailure>();

            if (string.IsNullOrEmpty(command.Email))
            {
                validationFailures.Add(new ValidationFailure("Email", ValidationFailureType.Missing));
            }
            else
            {
                try
                {
                    _readOnlyRepsitory.First <UserEmailLogin>(x => x.Email == command.Email);
                }
                catch (ItemNotFoundException <UserEmailLogin> )
                {
                    validationFailures.Add(new ValidationFailure("Email", ValidationFailureType.DoesNotExist));
                }
            }

            if (validationFailures.Any())
            {
                throw new CommandValidationException(validationFailures);
            }
        }
示例#19
0
        public LoginModule(
            IReadOnlyRepository readOnlyRepository, 
            IPasswordEncryptor passwordEncryptor,
            IUserSessionFactory userSessionFactory)
        {
            
            Post["/login"] =
                r =>
                    {
                        var loginInfo = this.Bind<LoginRequest>();

                        EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password);

                        try
                        {
                            var user =
                            readOnlyRepository.First<User>(
                                x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password);

                            if (!user.Activated) return new Response().WithStatusCode(HttpStatusCode.Forbidden);

                            var userSession = userSessionFactory.Create(user);

                            return new SuccessfulLoginResponse<Guid>(userSession.Id, userSession.Expires);
                        }
                        catch (ItemNotFoundException<User> ex)
                        {
                            return new Response().WithStatusCode(HttpStatusCode.Unauthorized);
                        }
                    };
        }
示例#20
0
        public UserModule(IMappingEngine mappingEngine, IReadOnlyRepository readOnlyRepository)
        {
            Get["/me"] = r =>
                             {
                                 return mappingEngine.Map<User, MeResponse>(this.UserSession().User);
                             };

            Get["/user/exists"] =
                r =>
                {
                    bool exists = false;
                    bool activated = false;
                    var facebookid = (long)Request.Query.facebookid;
                    try
                    {
                        var user =
                            readOnlyRepository.First<User>(x => x.FacebookId == facebookid);
                        if (user != null)
                        {
                            exists = true;
                            activated = user.Verified;
                        }

                    }
                    catch (ItemNotFoundException<User>)
                    {
                    }
                    return new UserExistenceResponse
                    {
                        Exists = exists,
                        Activated = activated,
                    };
                };
        }
        public void Handle(IUserSession userIssuingCommand, CreatePasswordResetToken command)
        {
            var  user    = _readOnlyRepository.First <UserEmailLogin>(x => x.Email == command.Email);
            Guid tokenId = _idGenerator.Generate();

            _writeableRepository.Create(new PasswordResetAuthorization(tokenId, user.Id, _timeProvider.Now()));
            NotifyObservers(new PasswordResetTokenCreated(tokenId, user.Id));
        }
示例#22
0
        public SuccessfulMessageResponse CreateCard([FromBody] CardsCreationModel model, string token, long laneId)
        {
            var session       = IsTokenExpired(token);
            var laneToAddCard = _readOnlyRepository.GetById <Lane>(laneId);
            var board         = _readOnlyRepository.First <Board>(board1 => board1.Lanes.Contains(laneToAddCard));
            var account       = _readOnlyRepository.First <Account>(account1 => account1.Id == session.User.Id);

            if (laneToAddCard != null && account != null)
            {
                var cardToAdd = _mappingEngine.Map <CardsCreationModel, Card>(model);
                cardToAdd.IsArchived = false;
                cardToAdd.Position   = laneToAddCard.Cards.Count() + 1;
                cardToAdd.AddMember(account);
                account.AddCard(cardToAdd);
                laneToAddCard.AddCards(cardToAdd);
                Card cardCreated = _writeOnlyRepository.Create(cardToAdd);
                if (cardCreated != null)
                {
                    string activityDone = "Add " + cardCreated.Text + " to " + board.Title;
                    board.AddActivity(ActivityHelper.CreateActivity(session.User, activityDone));
                    return(new SuccessfulMessageResponse("Lane was successfully created"));
                }
            }
            throw new BadRequestException("YThis Lane does not exist");
        }
        // DELETE api/folder/5
        public bool Delete([FromUri] string token, [FromUri] int id) // Borra un folder, y te retorna el root folder
        {
            var account = CheckPermissions(token);

            if (CheckCuenta(account))
            {
                var folder = _readOnlyRepository.First <File>(x => x.Id == id);
                if (folder != null)
                {
                    folder.IsArchived = true;
                    _writeOnlyRepository.Update(folder);
                    var model = new FolderModel();
                    model.listaModels = ListRootFolder(account);
                    return(true);
                }
            }
            return(false);
        }
示例#24
0
        public Sessions IsTokenExpired(string token)
        {
            var session = _readOnlyRepository.First <Sessions>(session1 => session1.Token == token);

            if (session.Duration >
                new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour,
                             DateTime.Now.Minute, DateTime.Now.Second))
            {
                return(session);
            }
            throw new BadRequestException("Your session has expired");
        }
示例#25
0
        public async Task <ActionResult <dynamic> > Authenticate([FromBody] User input)
        {
            var userRepositoryResponse = await _users.First(user => user.Login == input.Login && user.Password == input.Password);

            if (!userRepositoryResponse.Success)
            {
                return(NotFound(new { message = "Invalid Login / Password" }));
            }

            var token = TokenService.GenerateAuthenticationToken(userRepositoryResponse.Response);

            return(token);
        }
示例#26
0
 static void CheckForExistingUser(IReadOnlyRepository readOnlyRepository, NewUserRequest newUserRequest)
 {
     var exists = true;
     try
     {
         readOnlyRepository.First<User>(x => x.Email == newUserRequest.Email);                
     }
     catch
     {
         exists = false;
     }
     if (exists)
         throw new UserAlreadyExistsException();
 }
示例#27
0
 static void CheckForExistingFacebookUser(IReadOnlyRepository readOnlyRepository, NewUserRequest newUserRequest)
 {
     bool exists = true;
     try
     {
         readOnlyRepository.First<User>(x => x.FacebookId == newUserRequest.FacebookId);
     }
     catch
     {
         exists = false;
     }
     if (exists)
         throw new UserAlreadyExistsException();
 }
示例#28
0
        UserLoginSession GetUserSessionFromToken(Guid token)
        {
            UserLoginSession userLoginSession;

            try
            {
                userLoginSession = _readOnlyRepo.First <UserLoginSession>(x => x.Id == token);
            }
            catch (ItemNotFoundException <UserLoginSession> e)
            {
                throw new TokenDoesNotExistException();
            }
            return(userLoginSession);
        }
示例#29
0
        public BoardModel CreateBoard([FromBody] BoardsCreationModel model, string token, long idOrganization)
        {
            var session      = IsTokenExpired(token);
            var account      = _readOnlyRepository.First <Account>(account1 => account1.Id == session.User.Id);
            var organization = _readOnlyRepository.GetById <Organization>(idOrganization);
            var boardToAdd   = _mappingEngine.Map <BoardsCreationModel, Board>(model);

            boardToAdd.Administrador = account;
            boardToAdd.AddMember(account);
            boardToAdd.IsArchived = false;
            account.AddBoard(boardToAdd);
            organization.AddBoard(boardToAdd);
            Board boardCreated = _writeOnlyRepository.Create(boardToAdd);

            if (boardCreated != null)
            {
                string activityDone = "Add " + boardToAdd.Title;
                boardToAdd.AddActivity(ActivityHelper.CreateActivity(session.User, activityDone));
                return(new BoardModel {
                    Title = boardCreated.Title, Id = boardCreated.Id
                });
            }
            throw new BadRequestException("The board could not be created");
        }
示例#30
0
 public VerificationModule(IReadOnlyRepository readOnlyRepository, ICommandDispatcher commandDispatcher)
 {
     Post["/verify"] = r =>
                           {
                               var input = this.Bind<VerifyAccountRequest>();
                               try {
                                   readOnlyRepository.First<Verification>(
                                       x => x.EmailAddress == input.Email && x.VerificationCode == input.Code);
                               }catch(ItemNotFoundException<Verification>)
                               {
                                   return new Response().WithStatusCode(HttpStatusCode.Unauthorized);
                               }
                               commandDispatcher.Dispatch(new ActivateUser(input.Email));
                               return new Response().WithStatusCode(HttpStatusCode.OK);
                           };
 }
示例#31
0
        public ActionResult ListAllContent()
        {
            var userContent = new List <DiskContentModel>();

            //var actualPath = Session["ActualPath"].ToString();
            var actualFolder = Session["ActualFolder"].ToString();
            var userFiles    = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name).Files;


            foreach (var file in userFiles)
            {
                if (file == null)
                {
                    continue;
                }

                var fileFolder = file.Url.Split('\\');

                if (!file.IsArchived && fileFolder[fileFolder.Length - 2].Equals(actualFolder))
                {
                    userContent.Add(Mapper.Map <DiskContentModel>(file));
                }
            }

            if (userContent.Count == 0)
            {
                userContent.Add(new DiskContentModel
                {
                    Id           = 0,
                    ModifiedDate = DateTime.Now.Date,
                    Name         = "You can now add files to your account",
                    Type         = "none"
                });
            }

            return(View(userContent));
        }
示例#32
0
        public ActionResult LogIn(AccountLoginModel model)
        {
            var account = _readOnlyRepository.First <Account>(
                x => x.Email == model.Email && x.Password == model.Password);



            if (account != null)
            {
                List <string> roles = account.Roles.Select(x => x.Name).ToList();
                FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                SetAuthenticationCookie(model.Email, roles);
                return(RedirectToAction("Index")); //redirect to wanted view.
            }

            Error("Email and/or password incorrect");
            return(View(model));
        }
        public ActionResult ListFileSearchResult(string searchTxt)
        {
            var userData  = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name);
            var filesList = new List <FileSearchResult>();

            foreach (var file in userData.Files)
            {
                if (file.Name.ToLower().Contains(searchTxt.ToLower()))
                {
                    filesList.Add(Mapper.Map <File, FileSearchResult>(file));
                }
            }

            if (!filesList.Any())
            {
                Error("No results found!!!");
                filesList.Add(new FileSearchResult {
                    Name = " ", Type = " ", CreatedDate = DateTime.Now, Url = string.Empty
                });
            }


            return(View(filesList));
        }
        public ActionResult ListAllContent()
        {
            //var actualPath = Session["ActualPath"].ToString();
            IEnumerable <File> list = null;
            var userFiles           = list;

            var actualFolder = Session["ActualFolder"].ToString();

            if (actualFolder == "Shared")
            {
                var temp = _readOnlyRepository.First <FileShared>(x => x.UserReceive == User.Identity.Name);
                if (temp != null)
                {
                    userFiles = temp.Files;
                }
            }
            else
            {
                userFiles = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name).Files;
            }

            var userContent = new List <DiskContentModel>();

            if (userFiles != null)
            {
                foreach (var file in userFiles)
                {
                    if (file == null)
                    {
                        continue;
                    }
                    var fileFolderArray = file.Url.Split('/');
                    var fileFolder      = fileFolderArray.Length > 1
                        ? fileFolderArray[fileFolderArray.Length - 2]
                        : fileFolderArray.FirstOrDefault();



                    if (!file.IsArchived && fileFolder.Equals(actualFolder) && !string.Equals(file.Name, actualFolder))
                    {
                        userContent.Add(Mapper.Map <DiskContentModel>(file));
                    }
                    else if (!file.IsArchived && file.IsShared && actualFolder == "Shared")
                    {
                        userContent.Add(Mapper.Map <DiskContentModel>(file));
                    }
                }
            }

            if (userContent.Count == 0)
            {
                userContent.Add(new DiskContentModel
                {
                    Id           = 0,
                    ModifiedDate = DateTime.Now.Date,
                    Name         = "You can now add files to your account",
                    Type         = "none"
                });
            }

            return(View(userContent));
        }
示例#35
0
        public LoginModule(IPasswordEncryptor passwordEncryptor, IReadOnlyRepository readOnlyRepository,
                           IUserSessionFactory userSessionFactory, IMenuProvider menuProvider)
        {
            Post["/login"] =
                _ =>
            {
                var loginInfo = this.Bind <LoginRequest>();
                if (loginInfo.Email == null)
                {
                    throw new UserInputPropertyMissingException("Email");
                }
                if (loginInfo.Password == null)
                {
                    throw new UserInputPropertyMissingException("Password");
                }

                EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password);

                try
                {
                    var user =
                        readOnlyRepository.First <UserEmailLogin>(
                            x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password);

                    if (!user.IsActive)
                    {
                        throw new DisableUserAccountException();
                    }
                    UserLoginSession userLoginSession = userSessionFactory.Create(user);

                    return(new SuccessfulLoginResponse <Guid>(userLoginSession.Id, user.Name,
                                                              userLoginSession.Expires, menuProvider.getFeatures(userLoginSession.GetClaimsAsArray())));
                }
                catch (ItemNotFoundException <UserEmailLogin> )
                {
                    throw new UnauthorizedAccessException("Invalid email address or password. Please try again.");
                }
                catch (DisableUserAccountException)
                {
                    throw new UnauthorizedAccessException("Your account has been disabled. Please contact your administrator for help.");
                }
            };

            Post["/login/facebook"] = _ =>
            {
                var loginInfo = this.Bind <LoginSocialRequest>();
                if (loginInfo.Email == null)
                {
                    throw new UserInputPropertyMissingException("Email");
                }
                if (loginInfo.Id == null)
                {
                    throw new UserInputPropertyMissingException("Social Id");
                }

                try
                {
                    var user =
                        readOnlyRepository.First <UserFacebookLogin>(
                            x => x.Email == loginInfo.Email && x.FacebookId == loginInfo.Id);

                    if (!user.IsActive)
                    {
                        throw new DisableUserAccountException();
                    }

                    UserLoginSession userLoginSession = userSessionFactory.Create(user);

                    return(new SuccessfulLoginResponse <Guid>(userLoginSession.Id, user.Name, userLoginSession.Expires, menuProvider.getFeatures(userLoginSession.GetClaimsAsArray())));
                }
                catch (ItemNotFoundException <UserEmailLogin> )
                {
                    throw new UnauthorizedAccessException("Invalid facebook user, you need to register first.");
                }
                catch (DisableUserAccountException)
                {
                    throw new UnauthorizedAccessException("Your account has been disabled. Please contact your administrator for help.");
                }
            };
            Get["/roles"] =
                _ =>
            {
                this.RequiresAuthentication();
                return(Response.AsJson(menuProvider.getAllFeatures()));
            };


            Post["/login/google"] = _ =>
            {
                var loginInfo = this.Bind <LoginSocialRequest>();
                if (loginInfo.Email == null)
                {
                    throw new UserInputPropertyMissingException("Email");
                }
                if (loginInfo.Id == null)
                {
                    throw new UserInputPropertyMissingException("Social Id");
                }

                try
                {
                    var user =
                        readOnlyRepository.First <UserGoogleLogin>(
                            x => x.Email == loginInfo.Email && x.GoogleId == loginInfo.Id);

                    if (!user.IsActive)
                    {
                        throw new DisableUserAccountException();
                    }

                    UserLoginSession userLoginSession = userSessionFactory.Create(user);

                    return(new SuccessfulLoginResponse <Guid>(userLoginSession.Id, user.Name, userLoginSession.Expires, menuProvider.getFeatures(userLoginSession.GetClaimsAsArray())));
                }
                catch (ItemNotFoundException <UserEmailLogin> )
                {
                    throw new UnauthorizedAccessException("Invalid google user, you need to register first.");
                }
                catch (DisableUserAccountException)
                {
                    throw new UnauthorizedAccessException("Your account has been disabled. Please contact your administrator for help.");
                }
            };
        }
示例#36
0
        public LoginModule(
            IReadOnlyRepository readOnlyRepository,
            IUserSessionFactory userSessionFactory, IPasswordEncryptor passwordEncryptor)
        {
            Post["/login/facebook"] =
                r =>
                    {
                        var loginInfo = this.Bind<FacebookLoginRequest>();
                        try
                        {
                            var user =
                                readOnlyRepository.First<User>(x => x.FacebookId == loginInfo.FacebookId);

                            //if (!user.Verified) return new Response().WithStatusCode(HttpStatusCode.Forbidden);

                            UserSession userSession = userSessionFactory.Create(user);

                            return new SuccessfulLoginResponse<Guid>(userSession.Id, userSession.Expires);
                        }
                        catch (ItemNotFoundException<User> ex)
                        {
                            return new Response().WithStatusCode(HttpStatusCode.Unauthorized);
                        }
                    };

            Post["/login"] =
                r =>
                    {
                        var loginInfo = this.Bind<BasicLoginRequest>();
                        if (loginInfo.Email == null) throw new UserInputPropertyMissingException("Email");
                        if (loginInfo.Password == null) throw new UserInputPropertyMissingException("Password");

                        EncryptedPassword encryptedPassword = passwordEncryptor.Encrypt(loginInfo.Password);

                        try
                        {
                            var user =
                                readOnlyRepository.First<User>(
                                    x => x.Email == loginInfo.Email && x.EncryptedPassword == encryptedPassword.Password);

                            //if (!user.Activated) throw new ForbiddenRequestException();

                            UserSession userSession = userSessionFactory.Create(user);

                            return new SuccessfulLoginResponse<Guid>(userSession.Id, userSession.Expires);
                        }
                        catch (ItemNotFoundException<User>)
                        {
                            throw new UnauthorizedAccessException();
                        }
                    };

            Post["/logout"] =
                r =>
                    {
                        var loginInfo = this.Bind<FacebookLoginRequest>();
                        try
                        {
                            var session =
                                readOnlyRepository.First<UserSession>(x => x.User.FacebookId == loginInfo.FacebookId);

                            userSessionFactory.Delete(session.Id);

                            return new Response().WithStatusCode(HttpStatusCode.OK);
                        }
                        catch (ItemNotFoundException<UserSession> ex)
                        {
                            return new Response().WithStatusCode(HttpStatusCode.Unauthorized);
                        }
                    };
        }
示例#37
0
        internal bool PostPaypal(string tx, string producto)
        {
            var httpRequest = WebRequest.Create("https://www.sandbox.paypal.com/cgi-bin/webscr") as HttpWebRequest;

            if (httpRequest != null)
            {
                httpRequest.Method          = "POST";
                httpRequest.ProtocolVersion = HttpVersion.Version11;
                httpRequest.ContentType     = "application/x-www-form-urlencoded";
                using (Stream requestStream = httpRequest.GetRequestStream())
                {
                    byte[] parametersBuffer =
                        Encoding.ASCII.GetBytes(
                            "cmd=_notify-synch&tx=" + tx +
                            "&at=wm1BBPJzvOKS7VC0u3pUVnlwwwHHlRBtYGNcowtpX-hOr6PLVQIIbeMhYQa");
                    requestStream.Write(parametersBuffer, 0, parametersBuffer.Length);
                }
                var httpResponse = httpRequest.GetResponse();
                var streamReader = new StreamReader(httpResponse.GetResponseStream());
                var resultHtml   = streamReader.ReadToEnd();
                if (resultHtml.Contains("SUCCES"))
                {
                    var account   = _readOnlyRepository.First <Account>(x => x.EMail == User.Identity.Name);
                    var _tranVent = new RecibosVentas
                    {
                        Transaccion = tx,
                        UserCompro  = account.EMail,
                        IsArchived  = false,
                        Fecha       = DateTime.Now
                    };

                    if (producto == "200 GB")
                    {
                        account.SpaceLimit    = account.SpaceLimit + 204800;
                        _tranVent.Total       = 30;
                        _tranVent.Descripcion = "Compra de 200 GB";
                    }
                    else if (producto == "500 GB")
                    {
                        account.SpaceLimit    = account.SpaceLimit + 512000;
                        _tranVent.Total       = 100;
                        _tranVent.Descripcion = "Compra de 500 GB";
                    }
                    _tranVent = _writeOnlyRepository.Create <RecibosVentas>(_tranVent);

                    account.RecibosVentas_Id = _tranVent.Id;

                    _writeOnlyRepository.Update <Account>(account);

                    return(true);
                }
                else
                {
                    #region EnvioMail

                    var emailBody = new StringBuilder("<b>paypal payment failure, so active an account is free </b>");
                    emailBody.Append("<br/>");
                    emailBody.Append("<br/>");
                    emailBody.Append("<br/>");
                    emailBody.Append("<br/>");
                    emailBody.Append("<b>paypal payment failure, so active an account is free " + DateTime.Now.Day + "/" +
                                     DateTime.Now.Month +
                                     "/" + DateTime.Now.Year + "</b>");

                    MailSender.SendEmail(User.Identity.Name, "Activation Free", emailBody.ToString());

                    #endregion

                    return(false);
                }
            }
            return(false);
        }
        public void RenameFolder(long objectId, string oldObjectName, string newObjectName, string clientDateTime2)
        {
            var userData = _readOnlyRepository.First <Account>(a => a.EMail == User.Identity.Name);
            var fileData = userData.Files.FirstOrDefault(f => f.Id == objectId);

            var userFiles = userData.Files.Where(t => t.Url.Contains(fileData.Name));

            var clientDate = Convert.ToDateTime(clientDateTime2);
            var newFoldUrl = string.IsNullOrEmpty(fileData.Url) || string.IsNullOrWhiteSpace(fileData.Url)
                ? newObjectName + "/"
                : fileData.Url.Replace(oldObjectName, newObjectName) + fileData.Name + "/";

            var putFolder = new PutObjectRequest {
                BucketName = userData.BucketName, Key = newFoldUrl, ContentBody = string.Empty
            };

            AWSClient.PutObject(putFolder);

            foreach (var file in userFiles)
            {
                if (file == null)
                {
                    continue;
                }

                if (file.IsDirectory)
                {
                    RenameFolder(file.Id, oldObjectName, newObjectName, clientDateTime2);
                }
                else
                {
                    //Copy the object
                    var newUrl = file.Url.Replace(oldObjectName, newObjectName) + file.Name;

                    var copyRequest = new CopyObjectRequest
                    {
                        SourceBucket      = userData.BucketName,
                        SourceKey         = file.Url + file.Name,
                        DestinationBucket = userData.BucketName,
                        DestinationKey    = newUrl,
                        CannedACL         = S3CannedACL.PublicRead
                    };

                    AWSClient.CopyObject(copyRequest);

                    //Delete the original
                    var deleteRequest = new DeleteObjectRequest
                    {
                        BucketName = userData.BucketName,
                        Key        = file.Url + file.Name
                    };
                    AWSClient.DeleteObject(deleteRequest);

                    file.ModifiedDate = clientDate;
                    file.Url          = file.Url.Replace(oldObjectName, newObjectName);
                    _writeOnlyRepository.Update(file);
                }
            }//fin foreach

            var deleteFolderRequest = new DeleteObjectRequest
            {
                BucketName = userData.BucketName,
                Key        = fileData.Url + fileData.Name + "/"
            };

            AWSClient.DeleteObject(deleteFolderRequest);
            var newFolderUrl = fileData.Url.Replace(oldObjectName, newObjectName);

            fileData.Url = newFolderUrl;

            _writeOnlyRepository.Update(fileData);
        }