Inheritance: MonoBehaviour
Beispiel #1
0
 public ActionResult SignIn(LoginViewModel loginViewModel)
 {
     UserModel userModel = new UserModel();
     Mapper.Map(loginViewModel, userModel);
     AuthenticationServiceResponse response = _authenticationService.SignInUser(userModel, true);
     return Json(response, JsonRequestBehavior.AllowGet);
 }
Beispiel #2
0
 public JobBuilder(OrderModel order, UserModel userModel, IHRIDService hridService, Vendor vendor = null)
 {
     job = new Job(order, hridService.NextId("Job"));
     job.User = userModel;
     job.Vendor = vendor;
     job.ProfitShareResult = vendor?.Strategy?.Calculate(order.OrderCart.TotalToPay.Value);
 }
Beispiel #3
0
            public RedirectToRouteResult LogIn(UserModel log)
            {
                Diagnostics.Debug.WriteLine("LogIn");
                Diagnostics.Debug.WriteLine(log.Nombre);
                Diagnostics.Debug.WriteLine(log.Apellido);
                Diagnostics.Debug.WriteLine(log.User);
                Diagnostics.Debug.WriteLine(log.Password);
                Diagnostics.Debug.WriteLine(log.Correo);
                Diagnostics.Debug.WriteLine(log.Genero);
                Diagnostics.Debug.WriteLine(log.Celular);

                Sesion li = new Sesion();
                if (li.user == null)
                {
                    string usuario = log.User;
                    string clave = log.Password;

                    if (li.IniciarSesion(usuario, clave))
                        return RedirectToAction("Index", "Dashboard");

                    else
                        return RedirectToAction("LogIn", "LogIn");
                }
                else
                {
                    li.user = log.User;
                    li.key = log.Password;

                    return RedirectToAction("LogIn", "LogIn");
                }
            }
Beispiel #4
0
        public CheckResult ValidateUser(SmartCRMEntitiesModel context, UserModel model)
        {
            CheckResult result = CheckResult.Default;

            if (string.IsNullOrWhiteSpace(model.Username))
            {
                result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<UserModel>(x => x.Username), "Enter username!"));
            }

            if (string.IsNullOrWhiteSpace(model.Password))
            {
                result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<UserModel>(x => x.Password), "Enter password!"));
            }

            if (model.Username.Length < MinimumUsernameLength)
            {
                result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<UserModel>(x => x.Username), "Minimum required length of the Username is 3 symbols!"));
            }

            if (model.Password.Length < MinimumPasswordLength)
            {
                result.Details.Add(new CheckResultDetail(CheckResultDetail.ErrorType.Error, StaticReflection.GetMemberName<UserModel>(x => x.Password), "Minimum required length of the Password is 6 symbols!"));
            }

            return result;
        }
Beispiel #5
0
        public ActionResult Lock(UserModel usersModel)
        {
            try
            {
                if (usersModel != null)
                {
                    var user = _userRepository.GetUsersModelByUserNameAndPassword(usersModel.UserName,
                        usersModel.Password);
                    if (user != null)
                    {
                        Session["User"] = user;
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {

                        return RedirectToAction("Login", "Account");
                    }

                }
            }
            catch (Exception)
            {

                throw;
            }
            return RedirectToAction("Login", "Account");
        }
        public UserController()
        {
            userModel = new UserModel();

            vcommon = new dgCommon();
            vcommon.Width = 940;

            view = new ucUser();

            vcommon.Text = "User";
            view.Dock = DockStyle.Fill;

            vcommon.Controls.Add(view);

            vcommon.CancelButton = view.btnClose;

            view.dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);

            view.dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError);

            view.bindingSource1.DataSource = userModel.getAllUsers();

            view.toolBtnDelete.Click += new EventHandler(toolBtnDelete_Click);
            view.btnClose.Click += new EventHandler(btnClose_Click);
        }
Beispiel #7
0
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool Add(UserModel model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into UserInfo(");
            strSql.Append("Id,UserName,PassWord,AddTime)");
            strSql.Append(" values (");
            strSql.Append("@Id,@UserName,@PassWord,@AddTime)");
            SqlParameter[] parameters = {
                    new SqlParameter("@Id", SqlDbType.UniqueIdentifier,16),
                    new SqlParameter("@UserName", SqlDbType.VarChar,50),
                    new SqlParameter("@PassWord", SqlDbType.VarChar,50),
                    new SqlParameter("@AddTime", SqlDbType.DateTime)};
            parameters[0].Value = Guid.NewGuid();
            parameters[1].Value = model.UserName;
            parameters[2].Value = model.PassWord;
            parameters[3].Value = model.AddTime;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public void TestWithValidPost_ShouldCreatePostInDatabase()
        {
            var testPost = new Post()
                {
                    Title = "Test post",
                    Tags = new List<Tag>() { new Tag()
                        {
                            Name = "technology"
                        },
                       
                },
                    Text = "this is just a test post"
                };

            var testUser = new UserModel()
            {
                Username = "******",
                DisplayName = "VALIDNICK",
                AuthCode = new string('b', 40)
            };
            LoggedUserModel userModel = RegisterTestUser(httpServer, testUser);

            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = userModel.SessionKey;

            var response = httpServer.Post("api/posts", testPost, headers);
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
Beispiel #9
0
 private void btnLogin_Click(object sender, EventArgs e)
 {
     if (txtUserName.Text.Trim().Equals(""))
     {
         MetroMessageBox.Show(this, "请输入您需要登录的用户名 (ง •̀_•́)ง", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
         txtUserName.Focus();
     }
     else if (txtPassWord.Text.Equals(""))
     {
         MetroMessageBox.Show(this, "请输入您的密码以确认身份 (ง •̀_•́)ง", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
         txtPassWord.Focus();
     }
     else
     {
         LoginValidClient client = new LoginValidClient("BasicHttpBinding_ILoginValid", WCFServiceUrl.LoginServiceUrl);
         UserModel user = client.GetUserIdentity(txtUserName.Text.Trim(), txtPassWord.Text);
         if (user != null)
         {
             this.DialogResult = DialogResult.OK;
             User = user;
         }
         else
         {
             MetroMessageBox.Show(this, "您输入的用户名或密码有误 ◔ ‸◔?", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
     }
 }
Beispiel #10
0
        public HttpResponseMessage Post(UserModel model)
        {
            HttpResponseMessage response = new HttpResponseMessage();
            var user = model.ToEntity();
            int userId = userService.UserRegistrationAndUpdation("insert",user);
            if (model.Image != null)
            {
                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    // Get the uploaded image from the Files collection
                    var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

                    if (httpPostedFile != null)
                    {
                        string lastPart = Path.GetExtension(httpPostedFile.FileName);
                        string fileName = string.Format("{0}_{1}.{2}", httpPostedFile.FileName, userId, lastPart);
                        // Get the complete file path
                        var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Images/User"), httpPostedFile.FileName);

                        // Save the uploaded file to "UploadedFiles" folder
                        httpPostedFile.SaveAs(fileSavePath);
                    }
                }
            }
            response.Content = new StringContent("Registration Successfully", Encoding.Unicode);
            return response;
        }
Beispiel #11
0
        // Update is called once per frame
        public void UpdateInfo(UserModel userModel)
        {
            if (userModel != null) {
                username.text = "Username: "******"m") {
                    gender.text = "Gender: Male";
                } else if (userModel.info.gender == "f") {
                    gender.text = "Gender: Female";
                } else {
                    gender.text = "Gender: " + userModel.info.gender;
                }
                country.text = "Country: " + userModel.info.country;
                state.text = "State: " + userModel.info.state;

                if (userModel.info.thumbnailUrl != null) {
                    GetUserPic(userModel.info.thumbnailUrl);
                }
            } else {
                username.text = "";
                gender.text = "";
                country.text = "";
                state.text = "";
                userPic.sprite = null;
            }
        }
Beispiel #12
0
	    private async Task GetOrCreateUser()
	    {
            using (var scope = Container.BeginLifetimeScope())
            {
                var userService = scope.Resolve<IUserService>();
                var user = await userService.GetByIdAsync(User.Id);
                if (user == null)
                {
                    var result = await userService.AddUserAsync(new UserModelAdd { DeviceId = User.DeviceId });
                    if (result.IsSuccess)
                    {
                        User = result.Model;
                        SavePreference(SipperPreference.UserId, User.Id.ToString());
                        SavePreference(SipperPreference.DeviceId, User.DeviceId.ToString());
                    }
                    else
                    {
                        Log.Debug("@string/log_prefix", "User cannot be registered");
                    }
                }
                else
                {
                    User = user;
                }
            }
	    }
Beispiel #13
0
        public ActionResult SaveChanges(UserModel model)
        {
            if (!ModelState.IsValid)
                return null;

            T_User entity = UserModel.ModelToEntity(model);

            // Save add action
            if (model.user_id <= 0)
            {
                entity.user_password = "******";
                entity.user_date_subscription = DateTime.Now;

                _context.Add(entity);
                _context.SaveChanges();
                Log.Info(string.Format("Edit user id={0} name={1}", entity.user_id, entity.user_name));

                return GenerateJson(entity, true, "Nouveau utilisateur ajouté.");
            }
            // Save edit action
            else
            {
                _context.Edit(entity);
                _context.SaveChanges();
                Log.Info(string.Format("Create user id={0} name={1}", entity.user_id, entity.user_name));

                return GenerateJson(entity, false, "Utilisateur modifié.");
            }
        }
 private LoggedUserModel RegisterTestUser(InMemoryHttpServer httpServer, UserModel testUser)
 {
     var response = httpServer.Post("api/users/register", testUser);
     var contentString = response.Content.ReadAsStringAsync().Result;
     var userModel = JsonConvert.DeserializeObject<LoggedUserModel>(contentString);
     return userModel;
 }
        public HttpResponseMessage LoginUser(UserModel user)
        {
            IQueryable<User> users = this.userRepository.GetAll();

            var result = from u in users
                         where u.Username == user.Username && u.Password == user.Password
                         select u;

            User newUser = result.FirstOrDefault();
            if (newUser != null)
            {
                var rep = new DbUsersRepository(db);
                var sessionKey = rep.LoginUser(user.Username, user.Password);
                UserLoggedModel userModel = new UserLoggedModel()
                {
                    UserID = newUser.UserID,
                    Username = newUser.Username,
                    SessionKey = sessionKey
                };
                var responseMsg = Request.CreateResponse(HttpStatusCode.OK, userModel);
                return responseMsg;
            }
            else
            {
                var responseMsg = Request.CreateResponse(HttpStatusCode.NotFound);
                return responseMsg;
            }
        }
        public string Add(AddUserModel model)
        {
            if (ModelState.IsValid)
            {
                UserModel user = new UserModel();
                user.Code = model.Code;                             //登录名
                user.Password = "******".VariationMd5();            //默认密码

                user.Name = model.Name;                             //姓名
                user.Phone = model.Phone;                           //电话
                user.No = model.No;                                 //用户编号

                user.Departmentid = model.Departmentid.ToInt();     //部门
                user.Gender = model.Gender;                         //性别
                user.Age = model.Age;                               //年龄

                user.Status = model.Status;                         //用户状态
                user.Email = model.Email;                           //邮箱

                user.DelFlag = 0;                                   //有效状态
                user.CreateMan = SysConfig.CurrentUser.Id;          //创建人
                user.CreateTime = DateTime.Now;                     //创建时间
                int result = user.Insert().ToInt();

                if (result > 0)
                {
                    //记录操作日志
                    CommonMethod.Log(SysConfig.CurrentUser.Id, "Insert", "Sys_User");
                    return "1";
                }
            }
            return "0";
        }
        public HttpResponseMessage LoginUser(UserModel model)
        {
            var baseResponse = this.TryToExecuteOperation(() =>
            {
                this.ValidateUsername(model.Username);
                this.ValidateAuthCode(model.AuthCode);
                var usernameToLower = model.Username.ToLower();
                var user = repository.All()
                    .FirstOrDefault(usr => usr.Username == usernameToLower && usr.AuthCode == model.AuthCode);

                if (user == null)
                {
                    throw new InvalidOperationException("Username is not exist!");
                }

                if (user.SessionKey == null)
                {
                    user.SessionKey = this.GenerateSessionKey(user.UserId);
                    repository.Update(user.UserId, user);
                }

                var userModel = new LoggedUserModel()
                {
                    DisplayName = user.DisplayName,
                    SessionKey = user.SessionKey
                };

                var response = this.Request.CreateResponse(HttpStatusCode.Created, userModel);
                return response;
            });
            return baseResponse;
        }
        // GET: UserMgt
        public ActionResult Index()
        {
            UserModel model = new UserModel();
            string code = Request.QueryString["code"];
            string state = Request.QueryString["state"];
            if (!string.IsNullOrEmpty(code))
            {
                model.OpenId = HttpHelper.GetOpenIdByAuthCode(code, state);
            }
            try
            {
                ViewBag.GenderList = EnumHelper.GetEnumList(typeof(PublicEnum.Gender));
                ViewBag.IdTypeList = EnumHelper.GetEnumList(typeof(PublicEnum.IdType));
                ViewBag.ProvinceList = this.GetProvince();
                ViewBag.CityList = this.GetCities(DefaultProvinceId);
                ViewBag.DistrictList = this.GetDistricts(DefaultCityId);
            }
            catch (Exception exp)
            {

                ViewBag.Message = exp.Message;
            }

            return View("Index", model);
        }
Beispiel #19
0
        public UcPassAtt(WPro aPro, UserModel userModel)
        {
            _APro = aPro;
            _UserModel = userModel;

            InitializeComponent();
        }
        public UserModel GetUser(int userId)
        {
            UserModel model = new UserModel();

            User user = session.Load<User>(userId);
            return model.FilledBy(user);
        }
Beispiel #21
0
        public static void WriteDefaultLogin(UserModel user,bool isEnableDomain,bool isFirst=true)
        {
            try
            {
                if (isFirst)
                {
                    RegistryKey rekey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true);
                    if (rekey == null) return;
                    else
                    {
                        rekey.SetValue("AutoAdminLogon", "1");
                        rekey.SetValue("DefaultUserName", user.UserName);
                        rekey.SetValue("DefaultPassword", user.Password);
                        if (isEnableDomain)
                            rekey.SetValue("DefaultDomainName", user.Domain);
                        LogHelper.WriteLog("用户" + user.UserName + "自动登录,登录密码为:" + user.Password);
                    }
                    rekey.Close();
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("设置自动登录错误",ex);
            }
        }
        public void TestGetPostsByMissingTags_ShoudReturnValidPosts()
        {
            var testUser = new UserModel()
            {
                Username = "******",
                DisplayName = "VALIDNICK",
                AuthCode = new string('b', 40)
            };
            LoggedUserModel userModel = RegisterTestUser(httpServer, testUser);
            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = userModel.SessionKey;

            var testPost = new Post()
            {
                Title = "Test post",
                Tags = new List<Tag>() { new Tag()
                        {
                            Name = "technology"
                        },
                       new Tag()
                        {
                            Name = "it"
                        },
                },
                Text = "this is just a test post"
            };

            httpServer.Post("api/posts", testPost, headers);

            var response = httpServer.Get("api/posts?tags=wrongtag,wrongags", headers);

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            var responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.AreEqual("[]", responseContent);
        }
        public HttpResponseMessage LoginUser(UserModel model)
        {
            if (model.Username == null && model.Password == null)
            {
                var errResponse = this.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, "User Username and Password could not be null");
                throw new HttpResponseException(errResponse);
            }

            var entity = this.userRepository.All().
                Where(x => x.Username == model.Username && x.Password == model.Password).FirstOrDefault();

            if (entity == null)
            {
                var errResponse = this.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, string.Format("There is no such element"));
                throw new HttpResponseException(errResponse);
            }

            entity.IsOnline = true;
            entity = this.userRepository.Update(entity.Id, entity);
            var response =
                Request.CreateResponse(HttpStatusCode.OK, entity);
            response.Headers.Location = new Uri(Url.Link("DefaultApi",
                new { id = entity.Id }));

            return response;
        }
 // user entity => user model
 public static UserModel ToModel(this User entity)
 {
     var model = new UserModel();
     AutoMapper.Mapper.CreateMap<User, UserModel>();
     AutoMapper.Mapper.Map(entity, model);
     return model;
 }
Beispiel #25
0
    public static UserModel getInstance()
    {
        if(_instance == null)
            _instance = new UserModel();

        return _instance;
    }
Beispiel #26
0
 public void Update(UserModel updatedUser)
 {
     var existing = Get(updatedUser.Id.GetValueOrDefault());
     if (existing != null)
     {
         existing.DisplayName = updatedUser.DisplayName;
         existing.UserName = updatedUser.UserName;
         existing.ExternalId = updatedUser.ExternalId;
         existing.Name = updatedUser.Name;
         existing.DisplayName = updatedUser.DisplayName;
         existing.NickName = updatedUser.NickName;
         existing.ProfileUrl = updatedUser.ProfileUrl;
         existing.Emails = updatedUser.Emails;
         existing.Addresses = updatedUser.Addresses;
         existing.PhoneNumbers = updatedUser.PhoneNumbers;
         existing.Ims = updatedUser.Ims;
         existing.Photos = updatedUser.Photos;
         existing.UserType = updatedUser.UserType;
         existing.Title = updatedUser.Title;
         existing.PreferredLanguage = updatedUser.PreferredLanguage;
         existing.Locale = updatedUser.Locale;
         existing.Timezonoe = updatedUser.Timezonoe;
         existing.Active = updatedUser.Active;
         existing.Password = updatedUser.Password;
         existing.Groups = updatedUser.Groups;
         existing.X509Certificates = updatedUser.X509Certificates;
         existing.Meta = updatedUser.Meta;
     }
 }
Beispiel #27
0
        public static async Task<LG.Data.Models.Users.UserModel> Update(LG.Data.Models.Shared.Contact contact)
        {

            var phones = new List<PhoneBase>();


            var user = new UserModel()
            {
                CorporationRID = 10,
                ClientRID = contact.ContactForRID,
                EventAction = Action.Update,
                GeneralInfo = new PersonInfo()
                {
                    FName = contact.PersonInfo.FName,
                    MName = contact.PersonInfo.MName,
                    LName = contact.PersonInfo.LName
                }
            };

            user.EventAction = Models.Enums.Action.Update;

            contact.EventAction = ContactAction.Update;
            for (var i = 0; i < contact.Phones.Count; i++)
            {
               await LG.Data.Shared.ContactInfoService.SavePhone(contact, i);
            }
            var r3 = LG.Data.Shared.ContactInfoService.SavePersonInfo(user);
            await r3;
            if (r3.IsCompleted)
            {
                return user;
            }
            return null;
        }
Beispiel #28
0
        /// <summary>
        /// Adds a login attempt to a user's log.
        /// </summary>
        /// <param name="userModel">UserModel with new Data.</param>
        /// <returns>Number of affected rows, should be 1.</returns>
        public LoginLog AddLogEntry(UserModel userModel)
        {
            ClientIdentifier clientIdentifier = Entities.ClientIdentifier.FirstOrDefault(x => x.UserName == userModel.UserName);

            LoginLog loginLog = new LoginLog
                {
                    IpAdress = userModel.IpAdress,
                    TimeStamp = DateTime.Now,
                    UserAgent = userModel.UserAgent,
                    Success = 0

                };

            if (clientIdentifier != null)
            {
                clientIdentifier.LastLogin = DateTime.Now;

                if (clientIdentifier.LoginLog == null)
                           clientIdentifier.LoginLog = new Collection<LoginLog>();

                clientIdentifier.LoginLog.Add(loginLog);
            }

            Entities.SaveChanges();

            return loginLog;
        }
Beispiel #29
0
        public ActionResult UserAdd(UserModel usersModel, HttpPostedFileBase files)
        {
            try
            {
                if (Session["User"] == null) return RedirectToAction("Login", "Account");
                var sessionUser = (UserModel)Session["User"];
                if (usersModel != null)
                {
                    if (_userRepository.CheckTheUserNameByUserName(usersModel.UserName))
                    {
                        ModelState.AddModelError("", "Kullanıcı adı kullanılıyor!");
                        return View("AddUser", usersModel);
                    }

                    if (usersModel.Password != usersModel.ConfirmPassword)
                    {
                        ModelState.AddModelError("", "Sifreler Aynı Değil!");
                        return View("AddUser", usersModel);
                    }

                    var model = new UserModel
                    {
                        UserName = usersModel.UserName,
                        Password = usersModel.Password,
                        Name = usersModel.Name,
                        LastName = usersModel.LastName,
                        Email = usersModel.Email,
                        IsDeleted = false,
                        Phone = usersModel.Phone,
                        CreatedById = sessionUser.UserId
                    };
                    var user = _userRepository.AddNewUserByUserModel(model);
                    if ((files != null) && (files.ContentLength > 0) && !string.IsNullOrEmpty(files.FileName) &&
                        (files.ContentType == "image/jpeg" || files.ContentType == "image/png"))
                    {
                        using (System.Drawing.Image img = System.Drawing.Image.FromStream(files.InputStream))
                        {
                            byte[] file = new byte[files.InputStream.Length];
                            var reader = new BinaryReader(files.InputStream);
                            files.InputStream.Seek(0, SeekOrigin.Begin);
                            file = reader.ReadBytes((int)files.InputStream.Length);
                            if (user != null)
                            {
                                var updateUser = _userRepository.GetById(user.UserId);
                                updateUser.Avatar = file;
                                _userRepository.Update(updateUser);
                                _userRepository.Commit();
                            }
                        }
                    }
                }
                return RedirectToAction("UserList", "User");
            }
            catch (Exception)
            {

                throw;
            }
        }
 public UserTasksModel InsertUser(UserModel input)
 {
     input.FirstName = input.FirstName.Trim();
     input.LastName = input.LastName.Trim();
     var newUser = new UserTasksModel {User = input};
     _repository.Update(newUser);
     return newUser;
 }
Beispiel #31
0
 public SignUpAccountViewModel(UserModel _newUser, IEventAggregator events)
 {
     _events = events;
     newUser = _newUser;
     GetTypes();
 }
Beispiel #32
0
        public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticateModel model)
        {
            UserModel user = _userService.Authenticate(model.Email, model.password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            if (model.Email == "Adminaddvals1" && model.password == "Adminaddvals1")
            {
                // authentication successful so generate jwt token
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                        new Claim(ClaimTypes.Email, user.Email.ToString()),
                        new Claim(ClaimTypes.Name, user.FirstName.ToString() + " " + user.LastName.ToString()),
                        new Claim(ClaimTypes.Role, "Admin"),
                    }),
                    Expires            = DateTime.UtcNow.AddHours(24),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                user.TokenApi = tokenHandler.WriteToken(token);
                //Console.WriteLine(user.TokenApi);
                UserModel user1 = await GetUserDb(user.Email);

                UserCreateDto userCreateDto = new UserCreateDto();
                userCreateDto.Password  = user1.Password;
                userCreateDto.FirstName = user1.FirstName;
                userCreateDto.LastName  = user1.LastName;
                userCreateDto.Company   = user1.Company;
                userCreateDto.Group     = user1.Group;
                userCreateDto.Email     = user1.Email;
                userCreateDto.TokenApi  = user1.TokenApi;
                userCreateDto.idSkytap  = user1.idSkytap;

                await UpdateUser(userCreateDto);

                //await UserSignIn(userCreateDto);

                return(Ok(new { Token = user.TokenApi }));
            }
            else
            {
                // authentication successful so generate jwt token
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                        new Claim(ClaimTypes.Email, user.Email.ToString()),
                        new Claim(ClaimTypes.Name, user.FirstName.ToString() + " " + user.LastName.ToString()),
                        new Claim(ClaimTypes.Role, "User"),
                    }),
                    Expires            = DateTime.UtcNow.AddHours(24),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);

                user.TokenApi = tokenHandler.WriteToken(token);

                UserModel user1 = await GetUserDb(user.Email);

                UserCreateDto userCreateDto = new UserCreateDto();
                userCreateDto.Password  = user1.Password;
                userCreateDto.FirstName = user1.FirstName;
                userCreateDto.LastName  = user1.LastName;
                userCreateDto.Company   = user1.Company;
                userCreateDto.Group     = user1.Group;
                userCreateDto.Email     = user1.Email;
                userCreateDto.TokenApi  = user1.TokenApi;
                userCreateDto.idSkytap  = user1.idSkytap;

                await UpdateUser(userCreateDto);

                string urlFinal = await UserSignIn(userCreateDto);


                return(Ok(new { Token = user.TokenApi, urlFinal }));
                //return Ok($"{{\"url\":\"{urlFinal}\"}}");
            }
        }
        /// <summary>
        /// Get roles by user
        /// </summary>
        /// <param name="user">user model</param>
        /// <returns>return role</returns>
        public async Task <string> GetRol(UserModel user)
        {
            var roles = await _manager.GetRolesAsync(user);

            return(roles.Select(x => x).FirstOrDefault());
        }
Beispiel #34
0
        public async Task <User> CreateAsync(UserSubmit userSubmit, Guid createdById)
        {
            // Start transactions to allow complete rollback in case of an error
            BeginAllTransactions();

            try
            {
                userSubmit.Username = userSubmit.Username.Trim();
                userSubmit.Email    = userSubmit.Email.Trim();

                if (string.IsNullOrWhiteSpace(userSubmit.Password))
                {
                    throw new ItemNotProcessableException($"Password field required for user create.");
                }

                if (userSubmit.Avatar != null && !userSubmit.Avatar.IsBase64String())
                {
                    throw new ItemNotProcessableException($"Avatar field is not a valid base64 string.");
                }

                UserModel checkUserModel = await userRepository.GetByUsernameAsync(userSubmit.Username, false);

                if (checkUserModel != null)
                {
                    throw new ItemNotProcessableException($"User with user name '{userSubmit.Username}' already exists.");
                }

                var userModel = mapper.Map <UserModel>(userSubmit);
                // Check that the mapper did not assign a default GUID (happens if no GUID supplied).
                if (userModel.Id == Guid.Empty.ToString())
                {
                    userModel.Id = null;
                }

                userModel.ChangedBy = createdById;

                // Validate Authentication Mode
                if (userModel.LdapAuthenticationModeId == Guid.Empty)
                {
                    userModel.LdapAuthenticationModeId = null;
                }


                if (userModel.LdapAuthenticationModeId != null)
                {
                    var authMode = await ldapAuthenticationModeRepository.GetByIdAsync((Guid)userModel.LdapAuthenticationModeId, true);

                    if (authMode == null)
                    {
                        throw new ItemNotFoundException($"Ldap Authentication Mode '{userModel.LdapAuthenticationModeId}' not found.");
                    }

                    if (!(await ldapConnectionService.CheckIfUserExist(userSubmit.Username, (Guid)userSubmit.LdapAuthenticationModeId)))
                    {
                        throw new ItemNotFoundException($"User with username '{userSubmit.Username}' was not found on Ldap authentication mode '{userModel.LdapAuthenticationModeId}'.");
                    }
                }

                userModel.NormalizedEmail      = userSubmit.Email.ToUpper();
                userModel.NormalizedUserName   = userSubmit.Username.ToUpper();
                userModel.EmailConfirmed       = true;
                userModel.PhoneNumberConfirmed = (userModel.PhoneNumber != null);

                UserModel createdUser = await userRepository.CreateAsync(userModel, userSubmit.Password, isPlainTextPassword : true);

                await AssignRolesToUserFromRoleIdList(createdUser, userSubmit.RoleIds);
                await AssignTeamsToUserFromTeamIdList(createdUser, userSubmit.TeamIds);

                createdUser = await userRepository.UpdateAsync(createdUser);

                // All successful
                CommitAllTransactions();

                return(mapper.Map <User>(createdUser));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                RollbackAllTransactions();
                throw;
            }
        }
 public AplicacaoPrincipal(IIdentity identity, string[] roles, int id) : base(identity, roles)
 {
     Dados = UserModel.RecoverById(id);
 }
 public UserRoleViewModel()
 {
     UserModel = new UserModel();
     Roles     = System.Web.Security.Roles.GetAllRoles().ToList();
 }
Beispiel #37
0
 internal CachedSharedUser(DiscordClientBase client, UserModel model) : base(client, model)
 {
     Update(model);
 }
 public void InsertUser(UserModel user)
 {
     _sql.SaveData("dbo.spUser_Insert", user, "TulipData");
 }
 /// <summary>
 /// insert a user into the database
 /// </summary>
 public async Task InsertUser(UserModel user)
 {
     await userCollection.InsertOneAsync(user);
 }
Beispiel #40
0
 protected override List <string> GetSaveSql(UserModel user, ref T_AreaInfo t_area)
 {
     throw new NotImplementedException();
 }
Beispiel #41
0
        public async Task <UserModel> FindUser(string userName, string password)
        {
            UserModel user = await _userManager.FindAsync(userName, password);

            return(user);
        }
Beispiel #42
0
        /// <summary>
        /// 创建一个用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public UserModel Create(UserModel user)
        {
            var result = _dal.Insert <UserModel>(user);

            return(result);
        }
Beispiel #43
0
        public void ReturnTrueIfModelTableNameIsCorrect()
        {
            UserModel UserModel = new UserModel();

            Assert.AreEqual("usrUser_usr", UserModel.TableName());
        }
        public ResponseViewModel GetLogedInUserDetails(UserModel loginmodel)
        {
            try
            {
                var name  = User.Identity.Name;
                var name1 = HttpContext.Current.Request.LogonUserIdentity.GetUserId();
                using (AuthRepository _repo = new AuthRepository())
                {
                    // var result = (IdentityUser)_repo.GetUser(loginmodel.Email).Content;
                    var result = (IdentityUser)_repo.FindLogin(loginmodel.UserName, loginmodel.Password).Content;
                    if (result != null)
                    {
                        // Check for UserType
                        if (!string.IsNullOrEmpty(result.Id))
                        {
                            IdViewModel idViewModel = new IdViewModel();

                            idViewModel.UserId = result.Id;

                            var UserData = accountService.GetLogedInUserDetails(idViewModel).Content;

                            //UsersViewModel model = new UsersViewModel();
                            //var newuser = _NetUserrepository.FindBy(x => x.UserId == result.Id).FirstOrDefault();
                            //if (newuser != null)
                            //{
                            //    var contactmodel = _contactrepository.GetSingle(newuser.ContactID.Value);
                            //    newuser.UserContact = contactmodel;
                            //    model.UserID = newuser.UserId;
                            //    model.FirstName = newuser.UserContact.FirstName;
                            //    model.LastName = newuser.UserContact.LastName;
                            //    model.Email = newuser.UserContact.Email;
                            //    model.ContactId = newuser.UserContact.ID;
                            //    model.PhotoPath = newuser.UserContact.PhotoPath;
                            //    model.Mobile = newuser.UserContact.Mobile;
                            //    model.IsEmailConfirmed = result.EmailConfirmed;

                            //}


                            responseViewModel.IsSuccess = true;
                            responseViewModel.Content   = UserData;
                            responseViewModel.Message   = "Login Successfull.";
                        }
                        else
                        {
                            responseViewModel.ReturnMessage = new List <string>();
                            responseViewModel.ReturnMessage.Add("Invaid login details. Please try again with valid UserName and Password.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                responseViewModel.IsSuccess = false;
                if (responseViewModel.ReturnMessage != null && responseViewModel.ReturnMessage.Count > 0)
                {
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
                else
                {
                    responseViewModel.ReturnMessage = new List <string>();
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
            }
            return(responseViewModel);
        }
        public async Task <ResponseViewModel> ForgetPasswordUserDetails(UserModel loginmodel)
        {
            try
            {
                using (AuthRepository _repo = new AuthRepository())
                {
                    var result = (IdentityUser)_repo.GetUser(loginmodel.Email).Content;
                    if (result != null)
                    {
                        if (!string.IsNullOrEmpty(result.Id))
                        {
                            //UsersViewModel model = new UsersViewModel();

                            //var newuser = _NetUserrepository.FindBy(x => x.UserId == result.Id).FirstOrDefault();
                            //if (newuser != null)
                            //{
                            //    var contactmodel = _contactrepository.GetSingle(newuser.ContactID.Value);
                            //    newuser.UserContact = contactmodel;
                            //    model.UserID = newuser.UserId;
                            //    model.FirstName = newuser.UserContact.FirstName;
                            //    model.LastName = newuser.UserContact.LastName;
                            //    model.Email = newuser.UserContact.Email;
                            //    model.ContactId = newuser.UserContact.ID;
                            //    model.PhotoPath = newuser.UserContact.PhotoPath;
                            //}


                            var code = await UserManager.GeneratePasswordResetTokenAsync(result.Id);

                            var mailPath = System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplates/ForgotPassword.tpl.html");
                            //var tokencode = WebUtility.UrlEncode(code);
                            var tokencode = HttpUtility.UrlEncode(code);
                            //if (System.IO.File.Exists(mailPath))
                            //{
                            //    EmailViewModel emailVm = new EmailViewModel();
                            //    emailVm.MailTo = model.Email;
                            //    emailVm.MailSubject = "Please Reset Your Password";
                            //    try
                            //    {
                            //        string baseURL = ConfigurationManager.AppSettings["MainURL"].ToString();
                            //        string redirectURL = baseURL + "/Account/Resetpassword?UserId=" + result.Id + "&Code=" + tokencode;
                            //        var message = System.IO.File.ReadAllText(mailPath);
                            //        message = message.Replace("<#firstname#>", model.FirstName);
                            //        message = message.Replace("<#lastname#>", model.LastName);
                            //        message = message.Replace("<#redirectUrl#>", redirectURL);
                            //        emailVm.MailMessage = message;
                            //        Helper.SendEmail(emailVm);


                            //        //var encodedCode = HttpUtility.UrlEncode(code);
                            //        //await UserManager.SendEmailAsync(result.Id, "Reset Password", Request.RequestUri.GetLeftPart(UriPartial.Authority) + "/Account/Resetpassword?Code=" + encodedCode);



                            //    }
                            //    catch (Exception ex)
                            //    {

                            //    }
                            //}
                            responseViewModel.IsSuccess = true;
                            responseViewModel.Content   = null;
                            responseViewModel.Message   = "Email has been sent you. Please check your email.";



                            //EmailViewModel emailVm = new EmailViewModel();
                            //emailVm.MailTo = model.Email;
                            //emailVm.MailSubject = "Please Reset Your Password";

                            //var mailPath = System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplates/ForgotPassword.tpl.html");

                            //if (System.IO.File.Exists(mailPath))
                            //{
                            //    string urlhost = System.Web.HttpContext.Current.Request.Url.Host;
                            //    int urlport = System.Web.HttpContext.Current.Request.Url.Port;
                            //    string url = "https://" + urlhost + ":" + urlport + "/Account/Login";

                            //    var message = System.IO.File.ReadAllText(mailPath);
                            //    message = message.Replace("<#firstname#>", model.FirstName);
                            //    message = message.Replace("<#lastname#>", model.LastName);
                            //    message = message.Replace("<#redirectUrl#>", url);
                            //    message = message.Replace("<#pass#>", NewpassWord);

                            //    emailVm.MailMessage = message;
                            //}

                            //Foreal.Services.Common.Helper.SendEmail(emailVm);
                        }
                        else
                        {
                            responseViewModel.ReturnMessage = new List <string>();
                            responseViewModel.ReturnMessage.Add("Invalid Email Address. Please try again with valid Email Address.");
                        }
                    }
                    else
                    {
                        responseViewModel.IsSuccess = false;
                        if (responseViewModel.ReturnMessage != null && responseViewModel.ReturnMessage.Count > 0)
                        {
                            responseViewModel.ReturnMessage.Add("User does not exist");
                        }
                        else
                        {
                            responseViewModel.ReturnMessage = new List <string>();
                            responseViewModel.ReturnMessage.Add("User does not exist");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                responseViewModel.IsSuccess = false;
                if (responseViewModel.ReturnMessage != null && responseViewModel.ReturnMessage.Count > 0)
                {
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
                else
                {
                    responseViewModel.ReturnMessage = new List <string>();
                    responseViewModel.ReturnMessage.Add(ex.Message);
                }
            }
            return(responseViewModel);
        }
Beispiel #46
0
 public static void Patch(this RuleSetModel ruleSetModel, RuleSet ruleSet, UserModel user)
 {
     if (ruleSetModel == null) return;
     ruleSetModel.Name = ruleSet.Name;
     ruleSetModel.PatchBase(user);
 }
 public UserRoleViewModel(string userName)
 {
     UserModel            = new UserModel(MembershipUserExtended.GetUser(userName, false));
     Roles                = System.Web.Security.Roles.GetAllRoles().ToList();
     WeeklyTimeTrackModel = TimeTrackManager.GetCurrentWeekClockInOutTime(userName);
 }
Beispiel #48
0
 public void Update(UserModel um)
 {
     //Da.Update<UserModel>("update tblusers set UserLevelId = @0 where userid = @1", um.UserLevelId, um.UserId);
 }
Beispiel #49
0
        public ActionResult MenuLayout()
        {
            var currentUser = new User();

            if ((Session["CurrentUser"] == null) && (Request.Cookies[FormsAuthentication.FormsCookieName] != null))
            {
                var authUser = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;

                var userModel = new UserModel();
                currentUser = userModel.GetSpecificUser(authUser);

                Session.Remove("CurrentUser");
                Session.Remove("MenuLayout");
                Session.Add("CurrentUser", currentUser);
            }
            else
            {
                if (Session["CurrentUser"] != null)
                {
                    var loggedInUser = (User)Session["CurrentUser"];

                    var userModel = new UserModel();
                    currentUser = userModel.GetSpecificUser(loggedInUser.User_Id);
                }
            }

            var renderMenu = new Menu();

            if (Session["MenuLayout"] == null)
            {
                var menuModel = new MenuModel();
                var menu      = menuModel.GetSpecificMenu((int)MenuContainerEnum.PCMMenu);

                var authorizedRoles = new List <Role>();

                authorizedRoles = currentUser.Roles.ToList();

                if (currentUser.Groups.Any())
                {
                    foreach (var group in currentUser.Groups)
                    {
                        var groupRoles = group.Roles.Select(r => r).ToList();
                        authorizedRoles.AddRange(groupRoles);
                    }
                }

                // TODO Add delegation here as well

                var effectiveRoles = authorizedRoles.Distinct().ToList();

                var menuItems = menu.Menu_Items.ToList();

                Helpers.SetAuthorizedRolesVisibility(ref menuItems, effectiveRoles);

                renderMenu = menu.Menu_Items.Any() ? new Menu {
                    Menu_Items = new List <Menu_Item>(menuItems)
                } : null;

                Session["MenuLayout"] = renderMenu;
            }
            else
            {
                renderMenu = (Menu)Session["MenuLayout"];
            }

            return(PartialView("_MenuLayout", renderMenu));
        }
Beispiel #50
0
        public Task <bool> RegisterUser(UserModel userModel)
        {
            _userStore.Add(userModel);

            return(Task.FromResult(true));
        }
Beispiel #51
0
        public async Task <User> UpdateAsync(UserSubmit userSubmit, Guid updatedById)
        {
            // Start transactions to allow complete rollback in case of an error
            BeginAllTransactions();

            try
            {
                userSubmit.Username = userSubmit.Username.Trim();
                userSubmit.Email    = userSubmit.Email.Trim();

                if (userSubmit.Avatar != null && !userSubmit.Avatar.IsBase64String())
                {
                    throw new ItemNotProcessableException($"Avatar field is not a valid base64 string.");
                }

                UserModel userModel = await userRepository.GetByIdAsync(userSubmit.Uuid, true);

                if (userModel == null)
                {
                    throw new ItemNotFoundException($"User with ID '{userSubmit.Uuid}' not found when attempting to update a user using this ID!");
                }

                await ConfirmUniqueUserName(userModel, userSubmit);
                await ConfirmLdapLink(userModel, userSubmit);

                if (userSubmit.Avatar != null)
                {
                    userModel.Avatar = Convert.FromBase64String(userSubmit.Avatar);
                }
                else
                {
                    userModel.Avatar = null;
                }

                if (userSubmit.LdapAuthenticationModeId == Guid.Empty)
                {
                    userModel.LdapAuthenticationModeId = null;
                }
                else
                {
                    userModel.LdapAuthenticationModeId = userSubmit.LdapAuthenticationModeId;
                }

                userModel.Email                = userSubmit.Email;
                userModel.NormalizedEmail      = userSubmit.Email.ToUpper();
                userModel.FirstName            = userSubmit.Name;
                userModel.PhoneNumber          = userSubmit.PhoneNumber;
                userModel.PhoneNumberConfirmed = (userModel.PhoneNumber != null);
                userModel.Surname              = userSubmit.Surname;
                userModel.UserName             = userSubmit.Username;
                userModel.NormalizedUserName   = userSubmit.Username.ToUpper();
                userModel.ChangedBy            = updatedById;

                await AssignRolesToUserFromRoleIdList(userModel, userSubmit.RoleIds);
                await AssignTeamsToUserFromTeamIdList(userModel, userSubmit.TeamIds);

                UserModel updatedUser = await userRepository.UpdateAsync(userModel);

                // All successful
                CommitAllTransactions();

                return(mapper.Map <User>(updatedUser));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                RollbackAllTransactions();
                throw;
            }
        }
Beispiel #52
0
        public ActionResult UserDetails()
        {
            UserModel us = ((UserModel)Session["UserModel"]);

            return(View("UserDetails", us));
        }
 private void CleanUpUserModel(UserModel model)
 {
     model.FirstName = model.FirstName.UppercaseFirst().Trim();
     model.LastName  = model.LastName.UppercaseFirst().Trim();
     model.Email     = model.Email.ToLower().Trim();
 }
 protected override Task <ClaimsIdentity> CreateIdentityAsync(IServiceProvider serviceProvider, string authenticationType, UserModel model, CancellationToken cancellationToken)
 {
     return(Task.FromResult(new ClaimsIdentity(new Claim[] { new Claim("id", model.Id) }, authenticationType)));
 }
 /// <summary>
 /// Return SignInResults
 /// </summary>
 /// <param name="user"> user model</param>
 /// <param name="password">user password</param>
 /// <param name="locoOnFailure">lock on failure</param>
 /// <returns>Return success if creeds are corrects</returns>
 public async Task <SignInResult> CheckPasswordAsync(UserModel user, string password, bool locoOnFailure)
 {
     return(await _signInManager.CheckPasswordSignInAsync(user, password, locoOnFailure));
 }
Beispiel #56
0
 public async Task <string> Update([FromForm] UserModel userModel)
 {
     return(await _userService.Update(userModel));
 }
 public Task <bool> Edit(UserModel userModel)
 {
     throw new NotImplementedException();
 }
 public Task <bool> RegisterUser(UserModel userModel)
 {
     return(Task.FromResult(true));
 }
Beispiel #59
0
 // GET: User/Edit/5
 public void Edit([FromBody] UserModel user)
 {
     _userService.UpdateUser(user);
 }
 public Task UpdateUser(int id, UserModel userModel)
 {
     throw new NotImplementedException();
 }