Пример #1
0
        public void UserMapTest()
        {
            // Arrange
            var userMapper = new UserMapper();

            dynamic obj = new JObject();
            obj.id = "101";
            obj.login = "******";
            obj.created_at = "2016-10-20T14:28:53.572+11:00";
            obj.updated_at = "2016-11-20T14:28:53.572+11:00";
            obj.description = "Great!";
            obj.observations_count = "102";
            obj.identifications_count = "103";
            obj.original_user_icon_url = "http://iseahorse.org/john.jpg";

            var user = new User();

            // Act
            userMapper.Map(obj, user);

            // Assert
            Assert.AreEqual(user.Id, 101);
            Assert.AreEqual(user.Login, "john");
            Assert.AreEqual(user.CreatedAt, Convert.ToDateTime("2016-10-20T14:28:53.572+11:00"));
            Assert.AreEqual(user.UpdatedAt, Convert.ToDateTime("2016-11-20T14:28:53.572+11:00"));
            Assert.AreEqual(user.Description, "Great!");
            Assert.AreEqual(user.ObservationsCount, 102);
            Assert.AreEqual(user.IdentificationsCount, 103);
            Assert.AreEqual(user.Photo.Id, 0);
            Assert.AreEqual(user.Photo.Attribution, null);
            Assert.AreEqual(user.Photo.Uri.ToString(), "http://iseahorse.org/john.jpg");
        }
Пример #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string logUser;
            //IIdentity WinId = HttpContext.Current.User.Identity;
            //WindowsIdentity wi = (WindowsIdentity)WinId;
            //logUser = wi.Name.ToString().Substring(wi.Name.ToString().LastIndexOf("\\") + 1);

            logUser = Session["logUser"].ToString();

            UserView user = new UserMapper().GetUserByUserName(logUser);
            EmployeeView emp = new EmployeeMapper().Get(new Entities.EmployeeEntity() { Id = user.EmployeeId });

            NameSurnameLabel.Text = emp.ToString();
            PersonalNoLabel.Text = emp.PersonalNumber;
            EmployeeNoLabel.Text = emp.EmployeeNo;
            UsernameLabel.Text = logUser;
            JobLabel.Text = emp.Job;
            OrganizationUnitLabel.Text = emp.OrganizationalUnit;

            #warning only for hr for simple users set to the EmployeeId
            ReminderView view = new ReminderMapper().GetReminderByType(Entities.ReminderEnum.EmployeeNoContract, null);
            EmployeeWithoutContractCountLabel.Text = view.Count.ToString();
            EmployeesWithoutContractUrl.Attributes.Add("href", view.Url);

            view = new ReminderMapper().GetReminderByType(Entities.ReminderEnum.ContractExpire, null);
            ContractExpireCountLabel.Text = view.Count.ToString();
            ContractExpireUrl.Attributes.Add("href", view.Url);

            view = new ReminderMapper().GetReminderByType(Entities.ReminderEnum.LeaveRequest, null);
            LeaveRequestsCountLabel.Text = view.Count.ToString();
            LeaveRequestsUrl.Attributes.Add("href", view.Url);
        }
    public User RegisterUser(User user)
    {
      try
      {
        var check = this.VerifyUser(user.Id);
        if (check == false)
        {
          var membershipRepository = this.RepositoryFactory.GetMembershipRepository();
          var userMapper = new UserMapper();

          var userDto = userMapper.Map(user);
          var registeredUser = membershipRepository.CreateEntity(userDto);

          if (registeredUser != null)
          {
            var result = userMapper.Map(registeredUser);
            return result;
          }
          else
          {
            return null;
          }
        }
      }
      catch (Exception e)
      {
        throw new UserException(string.Empty, e);
      }

      return null;
    }
Пример #4
0
        public void Returns_null_when_guid_is_not_found()
        {
            var adapter = new InMemoryAdapter();
            Database.UseMockAdapter(adapter);

            var userMapper = new UserMapper();
            var identity = userMapper.GetUserFromIdentifier(Guid.NewGuid(), null);

            Assert.IsNull(identity);
        }
Пример #5
0
        public void Returns_useridenty_when_guid_is_found()
        {
            const string guid = "91e2403b-c568-4116-9c87-b6b71b6acbe4";
            const string userName = "******";

            var adapter = new InMemoryAdapter();
            Database.UseMockAdapter(adapter);

            var db = Database.Open();
            db.Users.Insert(Login: userName, HashedPassword: "******", Salt: "salt", Guid: guid);

            var userMapper = new UserMapper();
            var identity = userMapper.GetUserFromIdentifier(new Guid(guid), null);

            Assert.AreEqual(userName, identity.UserName);
        }
 public UserRepository(DatabaseConnection aContext)
 {
     context    = aContext;
     userMapper = new UserMapper();
     teamMapper = new TeamMapper();
 }
 public IUser GetUser(string accountName, AccountType accountType)
 {
     var mapper = new UserMapper();
     return mapper.Map(queryService.GetUser(accountName, (Querying.Data.AccountType)accountType));
 }
Пример #8
0
 public List <UserDTOM> GetAllUsers()
 {
     return(UserMapper.UsersToUsersModels(_userRepo.GetAll().ToList()));
 }
Пример #9
0
 public UserModel LogInUser(string username, string password)
 {
     return(UserMapper.UserToUserModel(_userRepo.GetAll().SingleOrDefault(u => u.Username == username && u.Password == password)));
 }
Пример #10
0
 public List <UserModel> GetAllUsers()
 {
     return(UserMapper.UsersToUserModels(_userRepo.GetAll()));
 }
Пример #11
0
        public AccountModule()
            : base("/account")
        {
            Get["/logon"] = parameters =>
            {
                base.Page.Title = "Login";

                var loginModel = new LoginModel();
                base.Model.LoginModel = loginModel;

                return(View["LogOn", base.Model]);
            };

            Post["/logon"] = parameters =>
            {
                var model  = this.Bind <LoginModel>();
                var result = this.Validate(model);

                var userMapper = new UserMapper(DocumentSession);
                var userGuid   = userMapper.ValidateUser(model.UserName, model.Password);

                if (userGuid == null || !result.IsValid)
                {
                    base.Page.Title = "Login";

                    foreach (var item in result.Errors)
                    {
                        foreach (var member in item.MemberNames)
                        {
                            base.Page.Errors.Add(new ErrorModel()
                            {
                                Name = member, ErrorMessage = item.GetMessage(member)
                            });
                        }
                    }

                    if (userGuid == null && base.Page.Errors.Count == 0)
                    {
                        base.Page.Errors.Add(new ErrorModel()
                        {
                            Name = "UserName", ErrorMessage = "Unable to find user"
                        });
                    }


                    base.Model.LoginModel = model;

                    return(View["LogOn", base.Model]);
                }

                DateTime?expiry = null;
                if (model.RememberMe)
                {
                    expiry = DateTime.Now.AddDays(7);
                }

                return(this.LoginAndRedirect(userGuid.Value, expiry));
            };

            Get["/logoff"] = parameters =>
            {
                return(this.LogoutAndRedirect("/"));
            };

            Get["/register"] = parameters =>
            {
                base.Page.Title = "Register";

                var registerModel = new RegisterModel();
                base.Model.RegisterModel = registerModel;


                return(View["Register", base.Model]);
            };

            Post["/register"] = parameters =>
            {
                var model  = this.Bind <RegisterModel>();
                var result = this.Validate(model);

                if (!result.IsValid)
                {
                    base.Page.Title = "Register";

                    base.Model.RegisterModel = model;

                    foreach (var item in result.Errors)
                    {
                        foreach (var member in item.MemberNames)
                        {
                            base.Page.Errors.Add(new ErrorModel()
                            {
                                Name = member, ErrorMessage = item.GetMessage(member)
                            });
                        }
                    }

                    return(View["Register", base.Model]);
                }

                var userMapper = new UserMapper(DocumentSession);
                var userGUID   = userMapper.ValidateRegisterNewUser(model);

                //User already exists
                if (userGUID == null)
                {
                    base.Page.Title          = "Register";
                    base.Model.RegisterModel = model;
                    base.Page.Errors.Add(new ErrorModel()
                    {
                        Name = "EmailAddress", ErrorMessage = "This email address has already been registered"
                    });
                    return(View["Register", base.Model]);
                }

                DateTime?expiry = DateTime.Now.AddDays(7);

                return(this.LoginAndRedirect(userGUID.Value, expiry));
            };



            Post["/token"] = parameters =>
            {
                string Apikey = ConfigurationManager.AppSettings["JanrainKey"];

                if (string.IsNullOrWhiteSpace(Request.Form.token))
                {
                    base.Page.Title       = "Login Error";
                    base.Model.LoginModel = "Bad response from login provider - could not find login token.";

                    return(View["Error", base.Model]);
                }

                var response = new WebClient().DownloadString(string.Format("https://rpxnow.com/api/v2/auth_info?apiKey={0}&token={1}", Apikey, Request.Form.token));

                if (string.IsNullOrWhiteSpace(response))
                {
                    base.Page.Title       = "Login Error";
                    base.Model.LoginModel = "Bad response from login provider - could not find user.";
                    return(View["Error", base.Model]);
                }

                var j = JsonConvert.DeserializeObject <dynamic>(response);

                if (j.stat.ToString() != "ok")
                {
                    base.Page.Title       = "Login Error";
                    base.Model.LoginModel = "Bad response from login provider - could not find login token.";
                    return(View["Error", base.Model]);
                }

                string userIdentity = j.profile.identifier.ToString();
                string displayName  = j.profile.displayName.ToString();
                string username     = j.profile.preferredUsername.ToString();
                string email        = string.Empty;
                if (j.profile.email != null)
                {
                    email = j.profile.email.ToString();
                }

                // var user = _user.GetUserFromUserIdentity(userIdentity);
                var user = DocumentSession.Query <UserModel, IndexUserLogin>().Where(x => x.LoginType == userIdentity).FirstOrDefault();

                if (user == null)
                {
                    UserModel newUser = new UserModel()
                    {
                        UserId       = Guid.NewGuid(),
                        EMailAddress = (!string.IsNullOrEmpty(email)) ? email : "*****@*****.**",
                        Username     = (!string.IsNullOrEmpty(username)) ? username : "******" + DocumentSession.Query <UserModel>().Count(),
                        LoginType    = userIdentity,
                        FriendlyName = displayName
                    };

                    DocumentSession.Store(newUser);
                    DocumentSession.SaveChanges();
                    return(this.LoginAndRedirect(newUser.UserId, DateTime.Now.AddDays(7)));
                }

                return(this.LoginAndRedirect(user.UserId, DateTime.Now.AddDays(7)));
            };
        }
Пример #12
0
        public bool DeleteUser(UserVM userViewModel)
        {
            var user = UserMapper.MapUserVMToUser(userViewModel);

            return(_userRepo.Delete(user));
        }
Пример #13
0
 public async Task Update(UserDto entity)
 {
     await _iUserRepository.Update(UserMapper.MapDtoToUser(entity));
 }
Пример #14
0
 public async Task Add(UserDto userDto)
 {
     await _iUserRepository.Add(UserMapper.MapDtoToUser(userDto));
 }
Пример #15
0
        public async Task <UserDto> GetById(long id)
        {
            var user = await _iUserRepository.GetById(id);

            return(UserMapper.MapUserToDto(user));
        }
Пример #16
0
 public UserService(IUserRepository repos)
 {
     Repository = repos;
     UserMapper.Map();
 }
Пример #17
0
 public async Task <IEnumerable <UserDTO> > GetAllModerators()
 {
     return(UserMapper.Map((await _userManager.GetUsersInRoleAsync("Moderator")).ToList()));
 }
 public ActionResult <IEnumerable <UserViewModel> > GetUsers()
 {
     return(_userService.GetAll().Select(x => UserMapper.DTOtoUserViewModel(x)).ToArray());
 }
Пример #19
0
        public IEnumerable <UserDto> GetUsersWithUserRole()
        {
            var users = _userRepository.GetList().ToList().Where((u => _userManager.IsInRole(u.Id, "User"))).ToList();

            return(UserMapper.MapToDto(users));
        }
Пример #20
0
        public void FromApiNode()
        {
            // ARRANGE
            Classification expectedClassification = Classification.Confidential;
            NodeType       expectedType           = NodeType.File;
            string         expectedTypeValue      = "file";

            Node expected = FactoryNode.Node;

            expected.Type           = expectedType;
            expected.Classification = expectedClassification;

            ApiNode param = new ApiNode {
                Id             = expected.Id,
                Type           = expectedTypeValue,
                ParentId       = expected.ParentId,
                ParentPath     = expected.ParentPath,
                Name           = expected.Name,
                MediaType      = expected.MediaType,
                MediaToken     = expected.MediaToken,
                Size           = expected.Size,
                Quota          = expected.Quota,
                Classification = (int)expected.Classification,
                Notes          = expected.Notes,
                Hash           = expected.Hash,
                ExpireAt       = expected.ExpireAt,
                CreatedAt      = expected.CreatedAt,
                CreatedBy      = new ApiUserInfo {
                    Id          = expected.CreatedBy.Id.Value,
                    AvatarUuid  = expected.CreatedBy.AvatarUUID,
                    DisplayName = expected.CreatedBy.DisplayName
                },
                UpdatedAt = expected.UpdatedAt,
                UpdatedBy = new ApiUserInfo {
                    Id          = expected.UpdatedBy.Id.Value,
                    AvatarUuid  = expected.UpdatedBy.AvatarUUID,
                    DisplayName = expected.UpdatedBy.DisplayName
                },
                InheritPermissions = expected.HasInheritPermissions,
                Permissions        = new ApiNodePermissions {
                    Manage = expected.Permissions.Manage,
                    Read   = expected.Permissions.Read,
                    Create = expected.Permissions.Create,
                    Change = expected.Permissions.Change,
                    Delete = expected.Permissions.Delete,
                    ManageDownloadShare = expected.Permissions.ManageDownloadShare,
                    ManageUploadShare   = expected.Permissions.ManageUploadShare,
                    ReadRecycleBin      = expected.Permissions.CanReadRecycleBin,
                    RestoreRecycleBin   = expected.Permissions.CanRestoreRecycleBin,
                    DeleteRecycleBin    = expected.Permissions.CanDeleteRecycleBin
                },
                IsFavorite                = expected.IsFavorite,
                IsEncrypted               = expected.IsEncrypted,
                CountChildren             = expected.CountChildren,
                CountFiles                = expected.CountFiles,
                CountRooms                = expected.CountRooms,
                CountFolders              = expected.CountFolders,
                CountDeletedVersions      = expected.CountDeletedVersions,
                RecycleBinRetentionPeriod = expected.RecycleBinRetentionPeriod,
                CountDownloadShares       = expected.CountDownloadShares,
                CountUploadShares         = expected.CountUploadShares,
                BranchVersion             = expected.BranchVersion,
                FileType = expected.Extension
            };

            Mock.Arrange(() => EnumConverter.ConvertValueToNodeTypeEnum(expectedTypeValue)).Returns(expectedType);
            Mock.Arrange(() => EnumConverter.ConvertValueToClassificationEnum((int)expectedClassification)).Returns(expectedClassification);
            Mock.Arrange(() => UserMapper.FromApiUserInfo(param.CreatedBy)).Returns(expected.CreatedBy);
            Mock.Arrange(() => UserMapper.FromApiUserInfo(param.UpdatedBy)).Returns(expected.UpdatedBy);

            // ACT
            Node actual = NodeMapper.FromApiNode(param);

            // ASSERT
            Assert.Equal(expected, actual, new NodeComparer());
        }
Пример #21
0
 public UserController()
 {
     _mapper = new UserMapper();
 }
Пример #22
0
 public UserService(IPasswordHasher <User> passwordHasher, UserRepository userRepository, UserMapper userMapper)
 {
     _passwordHasher = passwordHasher;
     _userRepository = userRepository;
     _userMapper     = userMapper;
 }
Пример #23
0
        public async Task <UserDTO> UpdatetUser(UserDTO user)
        {
            var result = UserDTOMapper.Map <User, UserDTO>(await UserProvider.UpdatetUser(UserMapper.Map <UserDTO, User>(user)));

            return(result);
        }
        public async Task <UserDto> HandleAsync(AuthenticateUser command)
        {
            var user = await _usersRepository.GetByEmail(command.Email);

            return((user != null && user.Password.VerifyPassword(command.Password)) ? UserMapper.From(user) : null);
        }
Пример #25
0
 public LoginServices(IRepository <User> userRepo, IRepository <Team> teamRepo)
 {
     userRepository = userRepo;
     mapper         = new UserMapper(teamRepo);
 }
Пример #26
0
        public AccountModule(IDbConnection db, ILog log, IRootPathProvider pathProvider)
            : base("/account")
        {
            Get["/logon"] = parameters => {
                base.Page.Title = "用户登录";

                //var loginModel = new LoginModel();
                var loginModel = new LoginModel()
                {
                    RememberMe = true
                };
                base.Model.LoginModel = loginModel;

                return(View["LogOn", base.Model]);
            };

            Post["/logon"] = parameters => {
                var model  = this.Bind <LoginModel>();
                var result = this.Validate(model);

                var userMapper = new UserMapper(db);
                var userGuid   = userMapper.ValidateUser(model.Email, model.Password);

                if (userGuid == null || !result.IsValid)
                {
                    base.Page.Title = "用户登录";

                    foreach (var item in result.Errors)
                    {
                        foreach (var member in item.Value)
                        {
                            base.Page.Errors.Add(new ErrorModel()
                            {
                                Name = item.Key, ErrorMessage = member.ErrorMessage
                            });
                        }
                    }

                    if (userGuid == null && base.Page.Errors.Count == 0)
                    {
                        base.Page.Errors.Add(new ErrorModel()
                        {
                            Name = "Email", ErrorMessage = "该用户不存在或密码输入错误"
                        });
                    }


                    base.Model.LoginModel = model;

                    return(View["LogOn", base.Model]);
                }

                DateTime?expiry = null;
                if (model.RememberMe)
                {
                    expiry = DateTime.Now.AddDays(100);
                }

                // 把临时购物车转到用户账下
                ConvertTempCar(db, pathProvider, userGuid);

                return(this.LoginAndRedirect(userGuid.Value, expiry));
            };

            Get["/logoff"] = parameters => {
                if (Session["TempUserId"] != null)
                {
                    Session.Delete("TempUserId");
                }
                if (Session["CarAdded"] != null)
                {
                    Session.Delete("CarAdded");
                }

                return(this.LogoutAndRedirect("/"));
            };

            Get["/register"] = parameters => {
                base.Page.Title = "用户注册";

                var registerModel = new RegisterModel();
                base.Model.RegisterModel = registerModel;

                return(View["Register", base.Model]);
            };

            Post["/register"] = parameters => {
                var model  = this.Bind <RegisterModel>();
                var result = this.Validate(model);

                if (!result.IsValid)
                {
                    base.Page.Title = "用户注册";

                    base.Model.RegisterModel = model;

                    foreach (var item in result.Errors)
                    {
                        foreach (var member in item.Value)
                        {
                            base.Page.Errors.Add(new ErrorModel()
                            {
                                Name = item.Key, ErrorMessage = member.ErrorMessage
                            });
                        }
                    }

                    return(View["Register", base.Model]);
                }

                var userMapper = new UserMapper(db);
                var userGuid   = userMapper.ValidateRegisterNewUser(model);

                //User already exists
                if (userGuid == null)
                {
                    base.Page.Title          = "用户注册";
                    base.Model.RegisterModel = model;
                    base.Page.Errors.Add(new ErrorModel()
                    {
                        Name = "Email", ErrorMessage = "Email已经存在了"
                    });
                    return(View["Register", base.Model]);
                    //return Response.AsRedirect("/account/register");
                }

                DateTime?expiry = DateTime.Now.AddDays(100);


                // 把临时购物车转到用户账下
                ConvertTempCar(db, pathProvider, userGuid);

                return(this.LoginAndRedirect(userGuid.Value, expiry));
            };

            Get["/findpwd"] = parameters => {
                base.Page.Title = "密码找回";
                return(View["FindPwd", base.Model]);
            };

            Post["/findpwd"] = parameters => {
                string email = Request.Form.Email;
                if (!Regex.IsMatch(email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"))
                {
                    base.Page.Errors.Add(new ErrorModel()
                    {
                        Name = "", ErrorMessage = "您输入的email格式不正确!"
                    });
                    return(Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest));
                }

                var user = db.Select <UserModel>(q => q.Email == email).FirstOrDefault();
                if (user == null)
                {
                    base.Page.Errors.Add(new ErrorModel()
                    {
                        Name = "", ErrorMessage = "您输入的email不存在!"
                    });
                    return(Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest));
                }

                //SMTP服务器
                SmtpClient smtp = new SmtpClient("smtp.qq.com"); //需要登陆邮箱到后台开启smtp/pop3服务
                smtp.Credentials = new NetworkCredential("87308217", "lina123");

                MailMessage mail = new MailMessage();
                mail.From = new MailAddress("*****@*****.**", "Bilin3D打印服务"); // 发件人
                mail.To.Add(email);                                            // 收件人
                mail.Subject      = "密码找回";
                mail.Body         = string.Format("<h4>你好,{0},您的登陆密码是:{1}</h4>", email, user.PassWord);
                mail.BodyEncoding = Encoding.UTF8;
                mail.IsBodyHtml   = true;
                mail.Priority     = MailPriority.Normal;
                try {
                    smtp.Send(mail);
                } catch (Exception ex) {
                    log.Error(ex.Message);
                    return(Response.AsJson(new { message = ex.Message }, Nancy.HttpStatusCode.BadRequest));
                }

                string domain    = email.Split('@').ToList().Last().ToLower();
                string email_url = "";
                if (domain == "qq.com")
                {
                    email_url = string.Format("<a href='{0}' target='_blank'>点击前往腾讯邮箱</a>", "http://mail.qq.com/");
                }
                if (domain == "163.com")
                {
                    email_url = string.Format("<a href='{0}' target='_blank'>点击前往网易邮箱</a>", "http://mail.163.com/");
                }

                //base.Page.Title = "密码找回成功";
                //base.Model.Message = string.Format(@"密码已发送到您的邮箱中了,请查收!   {0}", email_url);
                //return View["FindPwdResult", base.Model];
                return(Response.AsJson(new { message = string.Format(@"密码已发送到您的邮箱中了,请查收!   {0}", email_url) }));
            };

            Get["/info"] = parameters => {
                this.RequiresAuthentication();
                var user = db.Single <UserModel>("select * from t_user where Id=@Id", new { Id = Page.UserId });
                base.Page.Title = "个人信息";
                base.Model.User = user;
                return(View["Info", base.Model]);
            };

            Post["/info"] = parameters => {
                this.RequiresAuthentication();
                string avatars  = Request.Form.avatars;
                string nickname = Request.Form.nickname;
                string tel      = Request.Form.tel;
                string sql      = string.Format(@"
                    UPDATE t_user
                    SET                   
                        NickName = '{0}',
                        Tel = '{1}',
                        Avatars = '{2}',                                       
                        EditTime = NOW()                    
                    WHERE
	                    Id = '{3}';"    , nickname, tel, avatars, Page.UserId);
                db.ExecuteNonQuery(sql);
                return(Response.AsJson(new { message = "success" }));
            };

            Post["/info/uploadimg"] = parameters => {
                this.RequiresAuthentication();
                string uploadDirectory;
                uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads", "avatars");
                if (!Directory.Exists(uploadDirectory))
                {
                    Directory.CreateDirectory(uploadDirectory);
                }

                var file = Request.Files.First();

                if (file.Value.Length > 1024 * 1024 * 0.5)    //不能大于0.5MB(512kb)
                {
                    base.Page.Errors.Add(new ErrorModel()
                    {
                        Name = "", ErrorMessage = "文件不能大于512kb太大了"
                    });
                    return(Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest));
                }

                string   _filename = "", filename = "";
                string[] imgs = new string[] { ".jpg", ".png", ".gif", ".bmp", ".jpeg" };
                if (!imgs.Contains(System.IO.Path.GetExtension(file.Name).ToLower()))
                {
                    base.Page.Errors.Add(new ErrorModel()
                    {
                        Name = "", ErrorMessage = "文件格式不正确"
                    });
                    return(Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest));
                }
                _filename = Page.UserId + "$" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fffff") + "$" + file.Name;
                filename  = Path.Combine(uploadDirectory, _filename);
                using (FileStream fileStream = new FileStream(filename, FileMode.Create)) {
                    file.Value.CopyTo(fileStream);
                }

                return(Response.AsJson(new { filename = _filename }));
            };

            Get["/address"] = parameters => {
                this.RequiresAuthentication();
                var addresses = db.Select <AddressModel>(string.Format(@"
                        select *
                        from t_address
                        where userid='{0}'
                        ", Page.UserId));
                base.Page.Title      = "收货地址管理";
                base.Model.Addresses = addresses;
                return(View["Address", base.Model]);
            };

            Post["/address"] = parameters => {
                this.RequiresAuthentication();
                string id = Request.Form.id;
                int    i  = db.ExecuteNonQuery(string.Format(@"
                    delete from t_address where id='{0}' and UserId='{1}' ", id, Page.UserId));
                if (i < 1)
                {
                    return(Response.AsJson(new { message = "error" }, Nancy.HttpStatusCode.BadRequest));
                }
                return(200);
            };

            Get["/address/{id}"] = parameters => {
                this.RequiresAuthentication();
                string id      = parameters.id;
                var    address = db.Select <AddressModel>(string.Format(@"
                    select * from t_address where id='{0}' and UserId='{1}' ", id, Page.UserId)).FirstOrDefault();
                base.Page.Title    = address.Consignee;
                base.Model.Address = address;
                return(View["AddressEdit", base.Model]);
            };

            Post["/address/{id}"] = parameters => {
                this.RequiresAuthentication();
                var model  = this.Bind <AddressModel>();
                var result = this.Validate(model);

                if (!result.IsValid)
                {
                    base.Model.RegisterModel = model;

                    foreach (var item in result.Errors)
                    {
                        foreach (var member in item.Value)
                        {
                            base.Page.Errors.Add(new ErrorModel()
                            {
                                Name = item.Key, ErrorMessage = member.ErrorMessage
                            });
                        }
                    }
                    return(Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest));
                }

                string sql = "";
                if (model.State == "1")
                {
                    sql += string.Format(@"update t_address set state='0' where userid='{0}' and state='1';", Page.UserId);
                }
                sql += string.Format(@"
                    update t_address 
                    set Consignee='{0}', 
                        Province='{1}',
                        City='{2}',
                        Dist='{3}',
                        Address='{4}',
                        Tel='{5}',
                        Company='{6}',
                        State='{7}'
                    where id='{8}' and UserId='{9}';
                    ", model.Consignee, model.Province, model.City, model.Dist, model.Address,
                                     model.Tel, model.Company, model.State, model.Id, Page.UserId);
                db.ExecuteNonQuery(sql);
                return(200);
            };

            Post["/address/add"] = parameters => {
                this.RequiresAuthentication();
                var model  = this.Bind <AddressModel>();
                var result = this.Validate(model);

                if (!result.IsValid)
                {
                    base.Model.RegisterModel = model;
                    foreach (var item in result.Errors)
                    {
                        foreach (var member in item.Value)
                        {
                            base.Page.Errors.Add(new ErrorModel()
                            {
                                Name = item.Key, ErrorMessage = member.ErrorMessage
                            });
                        }
                    }

                    return(Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest));
                }

                var count = db.Select <string>(string.Format(@"
                    select count(1) from t_address where userid='{0}'", Page.UserId)).FirstOrDefault();
                if (count != null && int.Parse(count) > 20)
                {
                    base.Page.Errors.Add(new ErrorModel()
                    {
                        Name = "", ErrorMessage = "收货地址不能超过20个"
                    });
                    return(Response.AsJson(base.Page.Errors, Nancy.HttpStatusCode.BadRequest));
                }

                string sql = "";
                if (model.State == "1")
                {
                    sql += string.Format(@"update t_address set state='0' where userid='{0}' and state='1';", Page.UserId);
                }
                sql += string.Format(@"
                    insert into t_address(userid,company,Consignee,tel,Province,city,dist,address,state)
                        values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');
                ", Page.UserId, model.Company, model.Consignee, model.Tel, model.Province, model.City, model.Dist, model.Address, model.State);
                db.ExecuteNonQuery(sql);

                var address = db.Select <AddressModel>(string.Format(@"
                    select * from t_address where id=(select max(id) from t_address where userid='{0}')", Page.UserId)).FirstOrDefault();

                return(Response.AsJson(address));
            };
        }
Пример #27
0
 public UserModel GetUserById(int id)
 {
     return(UserMapper.UserToUserModel(_userRepo.GetById(id)));
 }
Пример #28
0
 public UserMapperTests()
 {
     this.mapper = new UserMapper();
 }
Пример #29
0
 public bool UpdateUser(UserModel user)
 {
     return(_userRepo.Update(UserMapper.UserModelToUser(user)));
 }
Пример #30
0
        public async Task <UserDto> GetUserAsync(int id)
        {
            var dbUser = await _userRepo.GetUserAsync(id);

            return(UserMapper.ToDto(dbUser));
        }
Пример #31
0
 public override void SetUp()
 {
     base.SetUp();
     sut = fixture.Create<UserMapper>();
 }
        public void EditUser(UserDTO userDto)
        {
            User user = UserMapper.MapToModel(userDto);

            this.repository.Edit(user);
        }
Пример #33
0
        public async Task <IActionResult> AddAdmin([FromBody] UserModel user)
        {
            var name = await _userService.AddUser(UserMapper.Map(user));

            return(Ok(name));
        }
Пример #34
0
 public UserController(IUserService userService, UserMapper userMapper)
 {
     _userService = userService;
     _userMapper  = userMapper;
 }
Пример #35
0
        public async Task <IActionResult> UpdateAdmin([FromBody] UserModel admin)
        {
            var name = await _userService.UpdateUser(UserMapper.Map(admin));

            return(Ok(name));
        }
Пример #36
0
        public async Task <UserDto> HandleAsync(GetUser query)
        {
            var user = await _usersRepository.GetById(query.Id);

            return(user == null ? null : UserMapper.From(user));
        }
Пример #37
0
        public AccountModule(IDocumentSession documentSession)
            : base("/account")
        {
            Get["/logon"] = parameters =>
            {
                Page.Title = "Login";

                var loginModel = new LoginModel();
                Model.LoginModel = loginModel;

                return View["LogOn", Model];
            };

            Post["/logon"] = parameters =>
                {
                    var model = this.Bind<LoginModel>();
                    var result = this.Validate(model);

                    var userMapper = new UserMapper(documentSession);
                    var userGuid = userMapper.ValidateUser(model.UserName, model.Password);

                    if (userGuid == null || !result.IsValid)
                    {
                        Page.Title = "Login";

                        foreach (var item in result.FormattedErrors)
                        {
                            foreach (var member in item.MemberNames)
                            {
                                Page.Errors.Add(new ErrorModel() { Name = member, ErrorMessage = item.GetMessage(member) });
                            }
                        }

                        if (userGuid == null && Page.Errors.Count == 0)
                            Page.Errors.Add(new ErrorModel() { Name = "UserName", ErrorMessage = "Unable to find user" });


                        Model.LoginModel = model;

                        return View["LogOn", Model];
                    }

                    DateTime? expiry = null;
                    if (model.RememberMe)
                    {
                        expiry = DateTime.Now.AddDays(7);
                    }

                    return this.LoginAndRedirect(userGuid.Value, expiry);
                };

            Get["/logoff"] = parameters =>
                {
                    return this.LogoutAndRedirect("/");
                };

            Get["/register"] = parameters =>
            {
                Page.Title = "Register";

                var registerModel = new RegisterModel();
                Model.RegisterModel = registerModel;


                return View["Register", Model];
            };

            Post["/register"] = parameters =>
                {
                    var model = this.Bind<RegisterModel>();
                    var result = this.Validate(model);

                    if (!result.IsValid)
                    {
                        Page.Title = "Register";

                        Model.RegisterModel = model;

                        foreach (var item in result.FormattedErrors)
                        {
                            foreach (var member in item.MemberNames)
                            {
                                Page.Errors.Add(new ErrorModel() { Name = member, ErrorMessage = item.GetMessage(member) });
                            }
                        }

                        return View["Register", Model];
                    }

                    var userMapper = new UserMapper(documentSession);
                    var userGUID = userMapper.ValidateRegisterNewUser(model);

                    //User already exists
                    if (userGUID == null)
                    {
                        Page.Title = "Register";
                        Model.RegisterModel = model;
                        Page.Errors.Add(new ErrorModel() { Name = "EmailAddress", ErrorMessage = "This email address has already been registered" });
                        return View["Register", Model];
                    }

                    DateTime? expiry = DateTime.Now.AddDays(7);

                    return this.LoginAndRedirect(userGUID.Value, expiry);
                };



            Post["/token"] = parameters =>
            {
                var Apikey = ConfigurationManager.AppSettings["JanrainKey"];

                if (string.IsNullOrWhiteSpace(Request.Form.token))
                {
                    Page.Title = "Login Error";
                    Model.LoginModel = "Bad response from login provider - could not find login token.";

                    return View["Error", Model];
                }

                var response = new WebClient().DownloadString(string.Format("https://rpxnow.com/api/v2/auth_info?apiKey={0}&token={1}", Apikey, Request.Form.token));

                if (string.IsNullOrWhiteSpace(response))
                {
                    Page.Title = "Login Error";
                    Model.LoginModel = "Bad response from login provider - could not find user.";
                    return View["Error", Model];
                }

                var j = JsonConvert.DeserializeObject<dynamic>(response);

                if (j.stat.ToString() != "ok")
                {
                    Page.Title = "Login Error";
                    Model.LoginModel = "Bad response from login provider - could not find login token.";
                    return View["Error", Model];
                }

                string userIdentity = j.profile.identifier.ToString();
                string displayName = j.profile.displayName.ToString();
                string username = j.profile.preferredUsername.ToString();
                var email = string.Empty;
                if (j.profile.email != null)
                    email = j.profile.email.ToString();

                var user = documentSession.Query<UserModel>().FirstOrDefault(x => x.LoginType == userIdentity);
                              
                if (user == null)
                {
                    var newUser = new UserModel()
                    {
                        Id = Guid.NewGuid(),
                        EMailAddress = (!string.IsNullOrEmpty(email)) ? email : "*****@*****.**",
                        Username = (!string.IsNullOrEmpty(username)) ? username : "******" + documentSession.Query<UserModel>().Count(),
                        LoginType = userIdentity,
                        FriendlyName = displayName
                    };

                    documentSession.Store(newUser);
                    documentSession.SaveChanges();
                    return this.LoginAndRedirect(newUser.Id, DateTime.Now.AddDays(7));
                }

                return this.LoginAndRedirect(user.Id, DateTime.Now.AddDays(7));
            };
        }
Пример #38
0
        private async Task <Response> UpdateUser()
        {
            Analytics.TrackEventAsync(Category.UserManagement, Action.Update, "Updated User", Username, CookieHelper.GetAnalyticClientId(Cookies));
            var body = Request.Body.AsString();

            if (string.IsNullOrEmpty(body))
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Could not save user, invalid JSON body"
                }));
            }

            var model = JsonConvert.DeserializeObject <UserManagementUpdateModel>(body);

            if (string.IsNullOrWhiteSpace(model.Id))
            {
                return(Response.AsJson(new JsonResponseModel
                {
                    Result = true,
                    Message = "Couldn't find the user"
                }));
            }

            var permissionsValue = model.Permissions.Where(c => c.Selected).Sum(c => c.Value);
            var featuresValue    = model.Features.Where(c => c.Selected).Sum(c => c.Value);

            Guid outId;

            Guid.TryParse(model.Id, out outId);
            var localUser = UserMapper.GetUser(outId);

            // Update Local User
            if (localUser != null)
            {
                localUser.Permissions = permissionsValue;
                localUser.Features    = featuresValue;

                var currentProps = ByteConverterHelper.ReturnObject <UserProperties>(localUser.UserProperties);

                // Let's check if the alias has changed, if so we need to change all the requests associated with this
                await UpdateRequests(localUser.UserName, currentProps.UserAlias, model.Alias);

                currentProps.UserAlias    = model.Alias;
                currentProps.EmailAddress = model.EmailAddress;

                localUser.UserProperties = ByteConverterHelper.ReturnBytes(currentProps);

                var user    = UserMapper.EditUser(localUser);
                var dbUser  = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == user.UserGuid);
                var retUser = MapLocalUser(user, dbUser?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            var plexDbUsers = await PlexUsersRepository.GetAllAsync();

            var plexUsers  = PlexApi.GetUsers(plexSettings.PlexAuthToken);
            var plexDbUser = plexDbUsers.FirstOrDefault(x => x.PlexUserId == model.Id);
            var plexUser   = plexUsers.User.FirstOrDefault(x => x.Id == model.Id);
            var userLogin  = UserLoginsRepo.GetAll().FirstOrDefault(x => x.UserId == model.Id);

            if (plexDbUser != null && plexUser != null)
            {
                // We have a user in the DB for this Plex Account
                plexDbUser.Permissions = permissionsValue;
                plexDbUser.Features    = featuresValue;

                await UpdateRequests(plexDbUser.Username, plexDbUser.UserAlias, model.Alias);

                plexDbUser.UserAlias    = model.Alias;
                plexDbUser.EmailAddress = model.EmailAddress;

                await PlexUsersRepository.UpdateAsync(plexDbUser);

                var retUser = MapPlexUser(plexUser, plexDbUser, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }

            // So it could actually be the admin
            var account = PlexApi.GetAccount(plexSettings.PlexAuthToken);

            if (plexDbUser != null && account != null)
            {
                // We have a user in the DB for this Plex Account
                plexDbUser.Permissions = permissionsValue;
                plexDbUser.Features    = featuresValue;

                await UpdateRequests(plexDbUser.Username, plexDbUser.UserAlias, model.Alias);

                plexDbUser.UserAlias = model.Alias;

                await PlexUsersRepository.UpdateAsync(plexDbUser);

                var retUser = MapPlexAdmin(account, plexDbUser, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }

            // We have a Plex Account but he's not in the DB
            if (plexUser != null)
            {
                var user = new PlexUsers
                {
                    Permissions  = permissionsValue,
                    Features     = featuresValue,
                    UserAlias    = model.Alias,
                    PlexUserId   = plexUser.Id,
                    EmailAddress = plexUser.Email,
                    Username     = plexUser.Title,
                    LoginId      = Guid.NewGuid().ToString()
                };

                await PlexUsersRepository.InsertAsync(user);

                var retUser = MapPlexUser(plexUser, user, userLogin?.LastLoggedIn ?? DateTime.MinValue);
                return(Response.AsJson(retUser));
            }
            return(null); // We should never end up here.
        }