Exemple #1
0
        public ReturnViewModel Create(UserBaseModel model)
        {
            var result = new ReturnViewModel();
            var entity = new User
            {
                Name    = model.UserName,
                Email   = model.Email,
                Balance = model.Balance,
                RoleId  = model.RoleId,
                GroupId = model.GroupId,
                AddedOn = DateTime.Now
            };

            try
            {
                _repository.Create(entity);
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                return(result);
            }
            result.Message   = entity.Id.ToString();
            result.IsSuccess = true;
            return(result);
        }
Exemple #2
0
        /// <summary>
        /// Метод выполняющий авторизацю пользователя
        /// </summary>
        /// <param name="email">Почта</param>
        /// <param name="passwordHash">Пароль пользователя</param>
        public BaseResponse <UserBaseModel> Login(string email, string passwordHash)
        {
            using (var db = new DataContext())
            {
                var user = db.Users.Include(x => x.Roles).FirstOrDefault(_ => _.Email == email && _.PasswordHash == passwordHash);
                if (user != null)
                {
                    if (user.Status != (int)EnumStatusUser.Active)
                    {
                        return(new BaseResponse <UserBaseModel>(EnumResponseStatus.ValidationError, Resource.ConfirmRegistrationSite));
                    }
                    var webUser = new UserBaseModel
                    {
                        Id        = user.Id,
                        Email     = user.Email,
                        FirstName = user.FirstName,
                        LastName  = user.LastName,
                        Roles     = user.Roles.Select(x => x.Name).ToList()
                    };

                    return(new BaseResponse <UserBaseModel>(webUser));
                }
                return(new BaseResponse <UserBaseModel>(EnumResponseStatus.ValidationError, Resource.WrongEmailOrPassword));
            }
        }
        public async Task <IActionResult> GenerateToken(LoginRequestModel login)
        {
            UserBaseModel user = await _userRepository.FindUserTaskAsync(login.Login, login.Password);

            if (user == null)
            {
                return(BadRequest());
            }
            user.Password = null;

            var token = new JwtSecurityToken(
                issuer: "Speckoz",
                audience: "Speckoz",
                claims: new[]
            {
                new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()),
                new Claim(ClaimTypes.Role, user.UserType.ToString()),
            },
                expires: DateTime.Now.AddYears(2),
                signingCredentials: new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"])),
                    SecurityAlgorithms.HmacSha256
                    ));

            return(Ok(new { user, token = new JwtSecurityTokenHandler().WriteToken(token) }));
        }
        public MessageModel UpdateSingleEntity(UserBaseModel model)
        {
            Func <IEntityContext, string> operation = delegate(IEntityContext context)
            {
                var data = context.UserBase.FirstOrDefault(m => m.UserID == model.UserID && m.ModifyTime == model.ModifyTime);
                if (data == null)
                {
                    return("当前数据不存在或被更新,请刷新后再次操作!");
                }
                data.UserCode   = model.UserCode;
                data.Password   = model.Password;
                data.UserName   = model.UserName;
                data.DeptID     = model.DeptID;
                data.CompanyID  = model.CompanyID;
                data.AreaCode   = model.AreaCode;
                data.Status     = model.Status;
                data.UserType   = model.UserType;
                data.IsLocked   = model.IsLocked;
                data.ModifyID   = UserManagement.CurrentUser.UserID;
                data.ModifyName = UserManagement.CurrentUser.UserName;
                data.ModifyTime = DateTime.Now;

                //data.UserDetail = userDetail;
                context.SaveChanges();
                return(string.Empty);
            };

            return(base.DbOperation(operation));
        }
Exemple #5
0
        public ActionResult Login(UserBaseModel model)
        {
            var passwordHash = model.Password.GetHashString();

            var loginStatus = _authCommonService.Login(model.Email, passwordHash);
            //todo:получать returnUrl параметром
            var returnUrl = HttpContext.Request.UrlReferrer.AbsoluteUri.Replace("/Admin/Home/Login?returnUrl=", "");

            if (loginStatus.IsSuccess)
            {
                var webUser = new WebUser()
                {
                    Email        = loginStatus.Value.Email,
                    IsAuthorized = true,
                    UserId       = loginStatus.Value.Id,
                    FirstName    = loginStatus.Value.FirstName,
                    LastName     = loginStatus.Value.LastName
                };
                System.Web.HttpContext.Current.Session["UserSession"] = webUser;
                _wishService.ComplementWishs(webUser.UserId);
                _userService.SetUserCookie(webUser.UserId);
                return(Json(new BaseResponse <string>(0, "Успешно", returnUrl)));
            }
            return(Json(loginStatus));
        }
        public bool CheckUserPass(UserBaseModel user)
        {
            INIT_QUERY_VARS(checkUserPassQuery);
            CallDBProcedure(user);
            var checkedUser = dataSaved[0];

            return(checkedUser != null);
        }
Exemple #7
0
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var resp = BaseResponseModel.Model <PlayersCountModelResponse>((ushort)MyResponseFlag.PlayersCount);

            resp.Count = mySocket.ParentServer.Clients.Count;

            mySocket.SendMessageToAll(resp);

            return(data);
        }
        public MessageModel InsertSingleEntity(UserBaseModel model)
        {
            Func <IEntityContext, string> operation = delegate(IEntityContext context)
            {
                //if (model.UserDetail == null) model.UserDetail = new UserDetailModel() ;
                context.UserBase.Add(model);
                context.SaveChanges();
                return(string.Empty);
            };

            return(base.DbOperation(operation));
        }
        private async Task GetLanguages(UserBaseModel model)
        {
            model.Languages = await _languageService.GetLanguagesForSelect();

            if (model.Languages == null || model.Languages.Count == 0)
            {
                AddMessageToModel(model, "Cannot retrieve languages, press F5 please.");
            }
            else
            {
                model.Languages.Last().Selected = true;
            }
        }
Exemple #10
0
        public string CreateAuthToken(UserBaseModel user)
        {
            var now      = DateTime.UtcNow;
            var identity = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Name)
            });
            var jwt = new JwtSecurityToken(AuthOptions.ISSUER,
                                           AuthOptions.AUDIENCE, identity.Claims, now, now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
                                           new SigningCredentials(AuthOptions.CreateSymmSecurityKey(), SecurityAlgorithms.HmacSha256));
            var res = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(res);
        }
        /// <summary>
        /// 新增用户数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public MessageModel InsertUserBase(UserBaseDto model)
        {
            var userBase = new UserBaseModel()
            {
                UserName   = model.UserName,
                UserCode   = model.UserCode,
                Password   = model.Password,
                DeptID     = model.DeptID,
                CompanyID  = model.CompanyID,
                AreaCode   = model.AreaCode,
                Status     = model.Status,
                UserType   = model.UserType,
                IsLocked   = model.IsLocked,
                CreateID   = UserManagement.CurrentUser.UserID,
                CreateName = UserManagement.CurrentUser.UserName,
                CreateTime = DateTime.Now
            };

            var userDetail = new UserDetailModel()
            {
                UserPhoto    = model.UserPhoto,
                EntryDate    = model.EntryDate,
                FormalDate   = model.FormalDate,
                LeaveDate    = model.LeaveDate,
                QQ           = model.QQ,
                BirthDay     = model.BirthDay,
                Email        = model.Email,
                IDCard       = model.IDCard,
                Mobile       = model.Mobile,
                Marriage     = model.Marriage,
                Gender       = model.Gender,
                Education    = model.Education,
                HomeAddress  = model.HomeAddress,
                Remark       = model.Remark,
                AttendanceNo = model.AttendanceNo,
                BankNo       = model.BankNo
            };
            Func <IEntityContext, string> operation = delegate(IEntityContext context)
            {
                context.UserBase.Add(userBase);
                context.SaveChanges();
                int uid = userBase.UserID;
                userDetail.UserID = uid;
                context.UserDetail.Add(userDetail);
                context.SaveChanges();
                return(string.Empty);
            };

            return(base.DbOperation(operation));
        }
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var thisModel = model.ToModel <PingModelRequest>();

            Console.WriteLine($"user float from ping {thisModel.Ping}");
            //Send ping return to client.
            var responseModel = BaseResponseModel.Model <PingModelResponse>((ushort)MyResponseFlag.Ping);

            responseModel.msg  = "abrakadabra";
            responseModel.Ping = thisModel.Ping;

            Console.WriteLine($"Received ping from {user.Name}");
            mySocket.SendMessage(responseModel);

            return(data);
        }
Exemple #13
0
        public void AddUser(UserBaseModel user)
        {
            using (var connection = new SurveyAppEntitiesConnection())
            {
                string globalId;
                var    surveyId = Int32.Parse(user.SelectedSurvey);
                //1. If user not there create one new
                var userId = (from u in connection.Users
                              where u.Name == user.Name && u.Email == user.Email
                              select u.Id).SingleOrDefault();

                if (userId == null || userId == 0)
                {
                    User u = new User()
                    {
                        Name  = user.Name,
                        Email = user.Email
                    };
                    connection.Users.Add(u);
                    connection.SaveChanges();

                    userId = (from newUser in connection.Users
                              where newUser.Name == user.Name && newUser.Email == user.Email
                              select newUser.Id).SingleOrDefault();
                }


                //2. Create GUID for that USer
                globalId = Guid.NewGuid().ToString();


                //3. create entry in USerSurvey table for Survey, User,Link,SurveyStatus
                SurveyLinkInfo link = new SurveyLinkInfo()
                {
                    GUID           = globalId,
                    UserId         = userId,
                    SurveyId       = surveyId,
                    SurveyStatusId = 1,    //(Not Started)
                    ApplicationKey = user.AppKey,
                    ClientId       = user.ClientId
                };
                connection.SurveyLinkInfoes.Add(link);
                connection.SaveChanges();
            }
        }
        public IActionResult Create([FromBody] UserBaseModel user)
        {
            if (user == null)
            {
                return(BadRequest("user is null"));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = _userService.Create(user);

            if (result.IsSuccess)
            {
                return(CreatedAtRoute("GetUser", new { id = long.Parse(result.Message) }, new { userId = result.Message }));
            }
            return(BadRequest(result));
        }
        private void AddUserBase()
        {
            UserBaseModel data = new UserBaseModel();

            data.UserCode   = "test";
            data.Password   = "******";
            data.UserName   = "******";
            data.DeptID     = 2;
            data.CompanyID  = 1;
            data.AreaCode   = "test";
            data.Status     = 1;
            data.UserType   = 1;
            data.IsLocked   = true;
            data.CreateID   = 1;
            data.CreateName = "test";
            data.CreateTime = DateTime.Now;
            IUserBaseService cs = new UserBaseService();
            var result          = cs.InsertSingleUserBase(data);
        }
Exemple #16
0
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var this_model = model.ToModel <LogModelRequest>();

            foreach (var i in this_model.msg)
            {
                Console.WriteLine("msg is:" + i);
            }

            var resp = BaseResponseModel.Model <LogModelResponse>((ushort)MyResponseFlag.LogResponse);

            resp.msg = new List <string>()
            {
                "qwe", "asd"
            };                                             //mySocket.ParentServer.Clients.Count;

            mySocket.SendMessage(resp);

            return(data);
        }
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var thisModel = model.ToModel <NewConnectionModelRequest>();

            //Update client information.
            user.IpAddress = mySocket.MscClient.Client.RemoteEndPoint.ToString();
            user.Name      = thisModel.Name;

            //Console Message.
            Console.WriteLine(user.IpAddress + $" connected. Name: {thisModel.Name}");
            Console.WriteLine(Convert.ToString(mySocket.ParentServer.Clients.Count) + " clients online.");

            var resp = BaseResponseModel.Model <PlayersCountModelResponse>((ushort)MyResponseFlag.PlayersCount);

            resp.Count = mySocket.ParentServer.Clients.Count;

            mySocket.SendMessageToAll(resp);

            return(data);
        }
        public ActionResult Login(UserBaseModel model)
        {
            // var user = iUserBaseService.GetUserBase(model.UserName, model.Password);
            string pwd  = EncodeStrToMd5.String32ToMD5(model.Password);
            var    user = iUserLoginService.GetUserLoginDto(model.UserName, pwd);

            if (user == null)
            {
                return(Json(new { success = false, msg = "用户名或密码错误" }));
            }
            var result = iUserLoginService.InsertSingleEntity(new LogUserLoginModel {
                UserID = user.UserID, LoginTime = DateTime.Now, NickName = user.UserName
            });

            Session["UserBase"] = user;
            //Session["Role"] = user == null ? null : user.Role;

            UserManagement.CurrentUser = user;

            return(Json(new { success = true, msg = "Find the User" }));
        }
Exemple #19
0
        public async System.Threading.Tasks.Task <DataResult <UserBaseModel> > Login(LoginModel model)
        {
            DataResult <UserBaseModel> result = new DataResult <UserBaseModel>();

            Entities.Tables.Identity.User user = await _userManager.FindByEmailAsync(model.Email.Trim());

            if (user == null || !(await _signInManager.CheckPasswordSignInAsync(user, model.Password, false)).Succeeded)
            {
                result.ResponseStatusType = ResponseStatusType.Error;
                result.Message            = ResponseMessageType.UserNotAuthorized;
            }
            else
            {
                await _signInManager.RefreshSignInAsync(user);

                UserBaseModel userModel = _mapper.Map <UserBaseModel>(user);
                result.ResponseStatusType = ResponseStatusType.Succeed;
                result.Data = userModel;
            }
            return(result);
        }
        public MessageModel InsertSingleEntity(UserBaseModel userBaseModel, UserDetailModel userDetailModel, List <int> roleModel)
        {
            Func <IEntityContext, string> operation = delegate(IEntityContext context)
            {
                context.UserBase.Add(userBaseModel);
                context.SaveChanges();
                int id = userBaseModel.UserID;
                userDetailModel.UserID = id;
                context.UserDetail.Add(userDetailModel);
                foreach (var item in roleModel)
                {
                    context.UserRole.Add(new UserRoleModel {
                        UserID = id, RoleID = item
                    });
                }
                context.SaveChanges();
                return(string.Empty);
            };

            return(base.DbOperation(operation));
        }
        public IActionResult Post([FromBody] UserBaseModel user)
        {
            var existingUser = repository.Users.FirstOrDefault(u => u.Name == user.Name);

            if (existingUser == null)
            {
                return(BadRequestResult("User not found"));
            }
            var manager = new UserManager(repository);

            if (!manager.CheckPass(user))
            {
                return(BadRequestResult("Incorrect password"));
            }

            var tokenString = manager.CreateAuthToken(user);
            var res         = new
            {
                access_token = tokenString,
                username     = user.Name
            };

            return(new JsonResult(res));
        }
Exemple #22
0
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            Console.WriteLine($"user {user.Name} respond to every 3s ping from server");

            return(data);
        }
 public MessageModel InsertSingleEntity(UserBaseModel userBaseModel, UserDetailModel userDetailModel, List <int> roleModel)
 {
     return(userBaseAccess.InsertSingleEntity(userBaseModel, userDetailModel, roleModel));
 }
 /// <summary>
 /// 编辑单条UserBase
 /// </summary>
 /// <param name="model">地块信息实体</param>
 /// <returns></returns>
 public MessageModel UpdateSingleUserBase(UserBaseModel model)
 {
     return(userBaseAccess.UpdateSingleEntity(model));
 }
 /// <summary>
 /// 新增单条UserBase
 /// </summary>
 /// <param name="model">地块信息实体</param>
 /// <returns></returns>
 public MessageModel InsertSingleUserBase(UserBaseModel model)
 {
     return(userBaseAccess.InsertSingleEntity(model));
 }
Exemple #26
0
 public bool CheckPass(UserBaseModel user)
 {
     return(repository.CheckUserPass(user));
 }
        //User accepts or rejects admin's request
        public async Task InviteHomeAcceptAsync(UserModel user, int invitedHomeId, bool isAccepted)
        {
            Task <InformationModel> firstNameInfo = _informationRepository.GetInformationByInformationNameAsync("FirstName");
            Task <InformationModel> lastNameInfo  = _informationRepository.GetInformationByInformationNameAsync("LastName");

            if (user.Position != (int)UserPosition.HasNotHome)
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("User Has Home", "User can not accept invite requests while already has home");
                errors.Throw();
            }

            HomeModel home = await _homeRepository.GetByIdAsync(invitedHomeId, true);

            if (home == null)
            {
                CustomException errors = new CustomException((int)HttpStatusCode.BadRequest);
                errors.AddError("Invalid Home Id", "Home not exist");
                errors.Throw();
            }

            if (isAccepted == true)
            {
                user.Position = (int)UserPosition.HasHome;

                UserInformationModel userFirstName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await firstNameInfo).Id);

                UserInformationModel userLastName = await _userInformationRepository.GetUserInformationByIdAsync(user.Id, (await lastNameInfo).Id);

                List <UserBaseModel> friendsBaseModels = new List <UserBaseModel>();
                UserBaseModel        userBaseModel     = new UserBaseModel(user.Id, user.Username, user.Position, userFirstName.Value, userLastName.Value, 0);

                FCMModel fcmUser = new FCMModel(user.DeviceId, type: "AllFriends");

                foreach (var friend in home.Users)
                {
                    FriendshipModel friendship       = new FriendshipModel(user, friend, 0);
                    Task            insertFriendship = _friendshipRepository.InsertAsync(friendship);

                    //Sends notification to all friends
                    FCMModel fcmFriend = new FCMModel(friend.DeviceId, new Dictionary <string, object>());

                    fcmFriend.notification.Add("title", "Yeni Ev Arkadaşı");
                    fcmFriend.notification.Add("body", String.Format("{0} {1}({2}) evinize katıldı", userFirstName.Value, userLastName.Value, user.Username));

                    await _fcmService.SendFCMAsync(fcmFriend);

                    //Sends notification to all friends
                    fcmFriend = new FCMModel(friend.DeviceId, new Dictionary <string, object>(), "NewFriend");
                    fcmFriend.data.Add("Friend", userBaseModel);

                    await _fcmService.SendFCMAsync(fcmFriend);

                    //Sends all friends to requester
                    UserInformationModel friendFirstName = await _userInformationRepository.GetUserInformationByIdAsync(friend.Id, (await firstNameInfo).Id);

                    UserInformationModel friendLastName = await _userInformationRepository.GetUserInformationByIdAsync(friend.Id, (await lastNameInfo).Id);

                    friendsBaseModels.Add(new UserBaseModel(friend.Id, friend.Username, friend.Position, friendFirstName.Value, friendLastName.Value, 0));

                    await insertFriendship;
                }

                home.Users.Add(user);
                _homeRepository.Update(home);

                user.Home = home;
                _userRepository.Update(user);

                fcmUser.data.Add("NumberOfFriends", home.Users.Count - 1);
                fcmUser.data.Add("Friends", friendsBaseModels);
                await _fcmService.SendFCMAsync(fcmUser);
            }
        }
 public MessageModel UpdateUserBase(UserBaseModel userbase, List <int> role)
 {
     return(userBaseAccess.UpdateSingleEntity(userbase));
 }
Exemple #29
0
 public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
 {
     Console.WriteLine($"Unhandled event {model.Flag} from user {user.Guid}");
     return(data);
 }
Exemple #30
0
        public bool AddUsersList(HttpRequest httpRequest)
        {
            try
            {
                IList <string> names  = new List <string>();
                IList <string> emails = new List <string>();

                if (httpRequest.Form["Name"] != "" && httpRequest.Form["Email"] != "")
                {
                    names.Add(httpRequest.Form["Name"]);
                    emails.Add(httpRequest.Form["Email"]);
                    if (UserExists(names, emails, httpRequest.Form["SelectedSurvey"]) == true)
                    {
                        return(false);
                    }
                    else
                    {
                        UserBaseModel user = new UserBaseModel()
                        {
                            AppKey         = httpRequest.Form["ApplicationKey"],
                            ClientId       = Int32.Parse(httpRequest.Form["ClientId"]),
                            SelectedSurvey = httpRequest.Form["SelectedSurvey"],
                            Name           = httpRequest.Form["Name"],
                            Email          = httpRequest.Form["Email"]
                        };
                        AddUser(user);
                        return(true);
                    }
                }
                else if (httpRequest.Files.Count > 0)   //if file exists in the form
                {
                    foreach (string file in httpRequest.Files)
                    {
                        var postedFile = httpRequest.Files[file];
                        var filePath   = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                        postedFile.SaveAs(filePath);

                        //now read the csv file
                        var reader = new StreamReader(File.OpenRead(filePath));

                        while (!reader.EndOfStream)
                        {
                            var      line   = reader.ReadLine();
                            string[] values = line.Split(',');
                            names.Add(values[0]);
                            emails.Add(values[1]);
                        }

                        if (UserExists(names, emails, httpRequest.Form["SelectedSurvey"]) == false)
                        {
                            return(false);
                        }
                        else
                        {
                            for (int i = 0; i < names.Count; i++)
                            {
                                UserBaseModel user = new UserBaseModel()
                                {
                                    AppKey         = httpRequest.Form["ApplicationKey"],
                                    ClientId       = Int32.Parse(httpRequest.Form["ClientId"]),
                                    SelectedSurvey = httpRequest.Form["SelectedSurvey"],
                                    Name           = names[i],
                                    Email          = emails[i]
                                };
                                //put code to validate Email address. If even one email address is not in proper format don't save the entire file and send back the error message to the view.
                                AddUser(user);
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }