/// <summary> /// Updating the user /// </summary> /// <param name="user"> The User model. </param> /// <returns> ApplicationUserDto object </returns> public ApplicationUserDto UpdateUser(ApplicationUserDto user) { try { user.ModifiedOn = DateTime.UtcNow; var newUser = this.mapperFactory.GetMapper<ApplicationUserDto, ApplicationUser>().Map(user); this.userRepository.Update(newUser); this.userRepository.Commit(); user = this.mapperFactory.GetMapper<ApplicationUser, ApplicationUserDto>().Map(newUser); } catch (Exception ex) { this.LoggerService.LogException("Updating User - " + ex.Message); } return user; }
/// <summary> /// The send activation email. /// </summary> /// <param name="user">The user.</param> /// <returns> /// The <see cref="bool" />. /// </returns> public bool SendActivationEmail(ApplicationUserDto user) { try { var emailQueueItem = new EmailQueue { TargetUserId = user.Id, MailChimpTemplateId = AppSettings.Get<long>("UserActivationMailChimpId", 0), EmailSubject = AppSettings.Get<string>("UserActivationEmailSubject", "Subject not defined"), SendVia = (int)EmailSendVia.ManDrill }; this.emailQueue.Insert(emailQueueItem); return this.emailQueue.Commit(); } catch (Exception) { throw; } }
/// <summary> /// Creates the asynchronous. /// </summary> /// <param name="user">The user.</param> /// <param name="userRole">The User Role. </param> /// <returns>IdentityResult object</returns> public async Task<IdentityResult> CreateAsync(ApplicationUserDto user, string userRole) { var result = new IdentityResult(); try { var u = this.mapperFactory.GetMapper<ApplicationUserDto, ApplicationUser>().Map(user); result = await this.userManager.CreateAsync(u); if (result != null && result.Succeeded) { this.userManager.AddToRole(user.Id, userRole); var newUser = this.mapperFactory.GetMapper<ApplicationUser, ApplicationUserDto>().Map(u); newUser.RoleName = userRole; user.RoleName = userRole; this.emailQueueService.SendActivationEmail(newUser); } } catch (Exception ex) { var a = ex.Message; } return result; }
/// <summary> /// Get Application User /// </summary> /// <param name="contactId"> The Contact Id. </param> /// <returns> ApplicationUserDto object</returns> public ApplicationUserDto GetContact(string contactId) { ApplicationUserDto user = new ApplicationUserDto(); try { ApplicationUser appUser = this.userRepository.First(x => x.Id == contactId) ?? new ApplicationUser(); user = this.mapperFactory.GetMapper<ApplicationUser, ApplicationUserDto>().Map(appUser); } catch (Exception ex) { this.LoggerService.LogException("Fetching contact :- " + ex.Message); } return user; }
public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) { ExternalLoginResultModel externalLoginResultModel = new ExternalLoginResultModel(); try { model.Country = string.IsNullOrWhiteSpace(model.Country) ? string.Empty : HttpUtility.UrlDecode(model.Country); ContactModel userModel = new ContactModel(); OrganisationModel orgModel = new OrganisationModel(); if (!this.ModelState.IsValid) { return this.BadRequest(this.ModelState); } var verifiedAccessToken = await this.VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken); if (verifiedAccessToken == null) { return this.BadRequest("Invalid Provider or External Access Token"); } var user = await this.authRepository.FindAsync(new UserLoginInfo(model.Provider, verifiedAccessToken.UserId)); bool hasRegistered = user != null; if (!hasRegistered) { userModel = this.GetExternalUserDetails(model.Provider, model.ExternalAccessToken); if (string.IsNullOrEmpty(userModel.Email)) { userModel.Email = model.Email; } userModel.GCMId = model.GCMId; userModel.UDId = model.UDId; userModel.OSType = model.OSType; userModel.MailingCountry = model.Country; userModel.MailingState = model.State; userModel.CountryCode = model.CountryCode; userModel.Timezone = model.Timezone; userModel.Latitude = model.Latitude; userModel.Longitude = model.Longitude; userModel.IsAvailable = true; userModel.Availability = Availability.AllDays; userModel.AvailableFrom = "08:00:00"; userModel.AvailableTo = "20:00:00"; userModel.IsOnline = true; userModel.IsActive = true; string userName = userModel.Email; if (string.IsNullOrWhiteSpace(userModel.Email)) { userName = Guid.NewGuid().ToString(); } user = new ApplicationUserDto { UserName = userName, Email = userModel.Email, Name = userModel.FirstName, AccountType = (short)model.UserRole }; if (model.Provider == "Facebook") { user.FacebookId = verifiedAccessToken.UserId; user.FBAccessToken = model.ExternalAccessToken; } else { user.GoogleId = verifiedAccessToken.UserId; user.GoogleAccessToken = model.ExternalAccessToken; } IdentityResult result = await this.authRepository.CreateAsync(user, model.UserRole.ToString()); if (!result.Succeeded) { string errorMessage = result.Errors.Any() ? result.Errors.First() : string.Empty; return this.BadRequest(errorMessage); } var info = new ExternalLoginInfo { DefaultUserName = model.UserName, Login = new UserLoginInfo(model.Provider, verifiedAccessToken.UserId) }; result = await this.authRepository.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { return this.GetErrorResult(result); } userModel.ImageURL = ImageHelper.SaveImageFromUrl(userModel.ImageURL, user.Id); if (model.UserRole == Roles.Company) { orgModel.AccountName = userModel.FirstName; orgModel.Email1 = userModel.Email; orgModel.FacebookURL = userModel.FBUrl; orgModel.GooglePlusURL = userModel.GooglePlusURL; orgModel.ImageURL = userModel.ImageURL; orgModel = this.crmManagerService.AddOrganisation(orgModel, user); } else { userModel = this.crmManagerService.AddContact(userModel, user); } } if (model.IsFromMobile) { var accessTokenResponse = this.GenerateLocalAccessTokenResponse(user); UserResultModel userResultModel = new UserResultModel(); OrgResultModel orgResultModel = new OrgResultModel(); CountryModel countryDet = this.commonService.GetUserCountryDetailsFromName(userModel.MailingCountry); if (model.UserRole == Roles.Customer) { userResultModel = this.mapperFactory.GetMapper<ContactModel, UserResultModel>().Map(userModel); userResultModel.ExternalAccessToken = accessTokenResponse; userResultModel.Rank = 0.0M; userResultModel.CountryDetails = countryDet; userResultModel.UserRole = Roles.Customer; userResultModel.IsActive = userModel.IsActive; userResultModel.PaymentDetails = new PaymentModelDto() { PayPalId = userModel.PaypalId, Mode = (PaymentMode)userModel.PaymentMode }; MessagesDto message = new MessagesDto(); message.ModifiedBy = message.FromUser = message.CreatedBy = "YoufferAdmin"; message.IsDeleted = false; message.CompanyId = AppSettings.Get<string>(ConfigConstants.SuperUserId); message.UserId = message.ToUser = user.Id; message.Name = "Youffer Admin"; message.MediaId = 0; MessageTemplatesDto msgTemplate = this.commonService.GetMessageTemplate(MessageTemplateType.WelcomeMsg); message.Message = msgTemplate.TemplateText; this.youfferMessageService.CreateMessage(message); int unreadMsgCount = this.youfferMessageService.GetUnreadMsgCount(message.UserId, false); if (!string.IsNullOrEmpty(userResultModel.GCMId)) { this.pushMessageService.SendMessageNotificationToAndroid(userResultModel.GCMId, message.Id.ToString(), message.Message, "Youffer", Notification.companymsg.ToString()); } if (!string.IsNullOrEmpty(userResultModel.UDId)) { this.pushMessageService.SendMessageNotificationToiOS(userResultModel.UDId, message.Id.ToString(), message.Message, "Youffer", unreadMsgCount, Notification.usermsg.ToString()); } return this.Ok(userResultModel); } else { orgResultModel = this.mapperFactory.GetMapper<OrganisationModel, OrgResultModel>().Map(orgModel); orgResultModel.ExternalAccessToken = accessTokenResponse.ToString(); orgResultModel.CountryDetails = countryDet; orgResultModel.UserRole = Roles.Company; orgResultModel.PaymentDetails = string.Empty; return this.Ok(orgResultModel); } } var redirectUri = string.Empty; var redirectUriValidationResult = this.ValidateClientAndRedirectUri(ref redirectUri); if (!string.IsNullOrEmpty(redirectUri)) { redirectUri = string.Format( "{0}?external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}", redirectUri, model.ExternalAccessToken, model.Provider, hasRegistered.ToString(), model.UserName); return this.Redirect(redirectUri); } externalLoginResultModel.ExternalAccessToken = model.ExternalAccessToken; externalLoginResultModel.Provider = model.Provider; externalLoginResultModel.HasLocalAccount = hasRegistered; externalLoginResultModel.ExternalUserName = model.UserName; } catch (Exception ex) { this.LoggerService.LogException("RegisterExternal : " + ex.Message); } return this.Ok(externalLoginResultModel); }
/// <summary> /// Generates the local access token response. /// </summary> /// <param name="user"> The Application user.</param> /// <returns>AccessTokenModel object</returns> private AccessTokenModel GenerateLocalAccessTokenResponse(ApplicationUserDto user) { var tokenExpiration = TimeSpan.FromDays(10); string roleName = user.RoleName; if (string.IsNullOrEmpty(roleName)) { roleName = this.authRepository.GetRoleName(user.Roles.ToList()[0].RoleId); } ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); identity.AddClaim(new Claim(ClaimTypes.Role, roleName)); identity.AddClaim(new Claim("sub", user.UserName)); identity.AddClaim(new Claim("role", roleName)); var props = new AuthenticationProperties { IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration), }; var ticket = new AuthenticationTicket(identity, props); var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); ////JObject tokenResponse = new JObject( //// new JProperty("userName", user.UserName), //// new JProperty("access_token", accessToken), //// new JProperty("userId", user.Id), //// new JProperty("token_type", "bearer"), //// new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString(CultureInfo.InvariantCulture)), //// new JProperty("issued", ticket.Properties.IssuedUtc.ToString()), //// new JProperty("expires", ticket.Properties.ExpiresUtc.ToString())); AccessTokenModel accessTokenModel = new AccessTokenModel(); accessTokenModel.UserName = user.UserName; accessTokenModel.AccessToken = accessToken; accessTokenModel.UserId = user.Id; accessTokenModel.TokenType = "bearer"; accessTokenModel.ExpiresIn = tokenExpiration.TotalSeconds.ToString(CultureInfo.InvariantCulture); accessTokenModel.Issued = ticket.Properties.IssuedUtc.ToString(); accessTokenModel.Expires = ticket.Properties.ExpiresUtc.ToString(); return accessTokenModel; }