protected UserProfileResponse GetUserProfileById(Guid userId) { var user = Context.UserInformation.Find(userId); if (user == null) { throw new Exception("User Not Found!"); } UserProfileResponse userResponse = new UserProfileResponse { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, PhoneNumber = user.PhoneNumber, BirthDate = user.DateOfBirth, ProfilePicture = user.ProfileImg == null ? null : GetDocumentResponseById((Guid)user.ProfileImg), Role = (Types.Constants.RoleType)user.RoleId, }; if (userResponse.Role == Types.Constants.RoleType.EMPLOYEE) { userResponse.Bio = user.Biography; GetEmployeeSpesificInfo(userResponse); } return(userResponse); }
public string HostpitalSearch() { string strJson = string.Empty; try { var token = Session["token"] == null ? "XXXXXXX" : Session["token"].ToString(); UserRequest user = new UserRequest(); HospitalSearchResponse hsr = new HospitalSearchResponse(); HospitalSearchResponse hsr80 = new HospitalSearchResponse(); UserProfileResponse userFile = user.profile(token, ""); if (userFile != null) { hsr = hospitalRequest.Search(token, 1, ""); } if (userFile.data.role == "80") { hsr80.code = hsr.code; hsr.message = hsr.message; hsr80.data = new HospitalSearchEntity(); hsr80.data.data = new List <HospitalEntity>(); hsr80.data.data.Add(hsr.data.data.Find(x => x.id == userFile.data.hospitalid)); hsr = hsr80; } if (hsr != null) { strJson = JsonHelper.SerializeObject(hsr); } } catch (Exception ex) { AppLog.Instance.Write("HostpitalSearch", AppLog.LogMessageType.Error, ex); } return(strJson); }
public async Task TestStream() { // Check that the user has an Xbox Music Pass subscription UserProfileResponse userProfileResponse = await AuthenticatedClient.GetUserProfileAsync(Namespace.music).Log(); // Beware: HasSubscription is bool?. You want != true instead of == false if (userProfileResponse.HasSubscription != true) { Assert.Inconclusive("The user doesn't have an Xbox Music Pass subscription. Cannot stream from catalog."); } // Get popular tracks in the user's country ContentResponse browseResults = await AuthenticatedClient.BrowseAsync(Namespace.music, ContentSource.Catalog, ItemType.Tracks).Log(); Assert.IsNotNull(browseResults, "The browse response should not be null"); AssertPaginatedListIsValid(browseResults.Tracks, 25, 100); // Stream the first streamable track Track track = browseResults.Tracks.Items.First(t => t.Rights.Contains("Stream")); StreamResponse streamResponse = await AuthenticatedClient.StreamAsync(track.Id, ClientInstanceId).Log(); Assert.IsNotNull(streamResponse, "The stream URL response should not be null"); Assert.IsNotNull(streamResponse.Url, "The stream URL should not be null"); Assert.IsNotNull(streamResponse.ContentType, "The stream content type should not be null"); Assert.IsNotNull(streamResponse.ExpiresOn, "The stream expiry date should not be null"); }
public UserProfileResponse RetrieveAllUserProfiles(UserProfileRequest obj) { UserProfileResponse result = new UserProfileResponse(); DbConnectionHandler dbConnectionHandler = new DbConnectionHandler(); DbConnection dbConnection = dbConnectionHandler.GetSqlConnection(obj.ConnString); SqlTransaction transaction = null; try { dbConnectionHandler.OpenDbConnection(dbConnection); transaction = (SqlTransaction)dbConnection.BeginTransaction(); UserProfileBL userProfileBL = new UserProfileBL(); result.UserProfileList = userProfileBL.RetrieveAllUserProfiles(obj.UserProfileType, dbConnection, transaction); } catch (Exception ex) { AppLog.GetAppLog().Log("Error: occurred in retrieving from query RetriveAllUserProfiles."); AppLog.GetAppLog().Log(ex.ToString()); AppLog.GetAppLog().HasError = true; throw ex; } finally { dbConnectionHandler.CloseDbConnection(dbConnection); } return(result); }
// GET: F8YLProject //public ActionResult ProjectList() //{ // var token = Session["token"] == null ? "XXXXXXX" : Session["token"].ToString(); // var currentUserId = Session["CurrentUserID"] == null ? "-1" : Session["CurrentUserID"].ToString(); // UserRequest user = new UserRequest(); // UserProfileResponse userFile = user.profile(token, currentUserId); // ProjectListResponse entData = new ProjectListResponse(); // if (userFile.data != null) // { // entData = projectRequest.list(token, userFile.data.hospitalid, 0, currentUserId); // } // ViewBag.UserFile = userFile.data; // ViewBag.ProjectList = entData.data.data; // return View(); //} #endregion public ActionResult ProjectList() { var token = Session["token"] == null ? "XXXXXXX" : Session["token"].ToString(); ViewBag.Token = token; var currentUserId = Session["CurrentUserID"] == null ? "-1" : Session["CurrentUserID"].ToString(); ViewBag.UserID = currentUserId; ViewBag.HospitalID = Session["hospitalid"] == null ? "-1" : Session["hospitalid"].ToString(); UserRequest user = new UserRequest(); UserProfileResponse userFile = user.profile(token, currentUserId); if (userFile.data.role == "90") { return(RedirectToAction("ManageIndex", "F8YLManage")); } ProjectJoined entData = new ProjectJoined(); if (userFile.data != null) { entData = projectRequest.Joined(token, "0"); } ViewBag.UserFile = userFile.data; ViewBag.ProjectList = entData.data; return(View()); }
public UserProfileResponse GenerateTokenLogout(string currentLogin) { UserProfileResponse response = new UserProfileResponse(); // return null if user not found // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(appSettings.KataKunciRahasiaku); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Email, currentLogin) }), Expires = DateTime.Now, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); response.Token = tokenHandler.WriteToken(token); return(response); }
public async Task <IActionResult> GetById([FromRoute] Guid profileId) { var profile = await _profileService.GetProfileByIdAsync(profileId); if (profile == null) { return(NotFound(new GenericResponse { Status = "Error", Message = "Oops, User does not exist" })); } var validateCompletion = ValidateProfile(profile.FirstName, profile.LastName, profile.Email, profile.Address, profile.ProfilePicture, profile.DOB); var response = new UserProfileResponse { Id = profile.Id, FirstName = profile.FirstName, LastName = profile.LastName, Email = profile.Email, Address = profile.Address, ProfilePcture = profile.ProfilePicture, DOB = profile.DOB, Status = validateCompletion }; return(Ok(response)); }
/// <summary> /// Gets the userProfiles. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public UserProfileResponse GetUserProfiles(UserProfileRequest request) { var response = new UserProfileResponse(); if (request.LoadOptions.Contains("UserProfiles")) { response.UserProfiles = request.LoadOptions.Contains("Active") ? UserProfileDao.GetUserProfiles(request.IsActive) : UserProfileDao.GetUserProfiles(); } if (request.LoadOptions.Contains("UserProfile")) { if (request.LoadOptions.Contains("UserProfileName")) { var userProfile = UserProfileDao.GetUserProfileByUserProfileName(request.UserProfileName, request.Password); if (userProfile == null) { response.Acknowledge = AcknowledgeType.Failure; response.Message = @"Tên đăng nhập hoặc mật khẩu không hợp lệ !"; return(response); } response.UserProfile = userProfile; } else { response.UserProfile = UserProfileDao.GetUserProfile(request.UserProfileId); } } return(response); }
public UserProfileResponse GetUserSSODetails(string ssoguid) { IServiceRequest proxy; UserProfileResponse response = null; UserProfileRequest request = null; try { proxy = ServiceRequestFactory.GetProxy(SERVICES.USERPROFILE_SERVICE); request = new UserProfileRequest(); request.SSOGUID = ssoguid; response = proxy.Request <UserProfileRequest, UserProfileResponse>(request); if (null != response) { if (response.Fault != null) { // log error Sitecore.Diagnostics.Log.Error(response.Fault, this); } else { return(response); } } } catch (Exception ex) { Sitecore.Diagnostics.Log.Error("Unable to get user details for SSOGUID " + ssoguid + " from User Profile service", ex, this); throw ex; } return(response); }
public UserProfileResponse GenerateToken(UserProfileResponse request) { // return null if user not found if (request.IsSuccess) { // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(appSettings.KataKunciRahasiaku); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Email, request.UserProfile.Email) }), Expires = DateTime.Now.AddHours(12), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); request.Token = tokenHandler.WriteToken(token); } return(request); }
public async Task GetUserSettingsTest() { var service = new Mock <ISettingsService>(); var response = new UserProfileResponse { Email = "alex@", FirstName = "alex", Language = LanguageName.Fr, LastName = "softeq", PhoneNumber = "123" }; service.Setup(x => x.GetUserSettingsAsync(It.Is <UserRequest>(sr => sr.UserId == UserId))) .ReturnsAsync(response) .Verifiable(); var controller = new SettingsController(_logger, service.Object).WithUser(); var result = await controller.GetUserSettingsAsync(); service.Verify(); var res = Assert.IsType <OkObjectResult>(result); Assert.Equal(response, res.Value); Assert.IsType <UserProfileResponse>(res.Value); }
public async Task <UserProfileResponse> Authenticate(UserProfileRequest request) { UserProfileResponse response = new UserProfileResponse(); try { request.Password = EncryptString(request.Password); var queryResult = await iUserProfile.GetUserProfile(request.Email, request.Password); if (queryResult != null) { response.UserProfile = new UserProfileViewModel() { UserId = queryResult.UserId, Email = queryResult.Email, Password = queryResult.Password, GenderId = queryResult.GenderId, FirstName = queryResult.FirstName, LastName = queryResult.LastName, Age = queryResult.Age }; return(response); } response.IsSuccess = false; response.Message = "Email and Password not Found!!!"; } catch (Exception ex) { response.Message = "Something Error in Our System : " + ex.Message; response.IsSuccess = false; } return(response); }
public async Task <UserProfileResponse> SetProfilePicture(UploadImageRequest req, int userId) { var profileModel = await _dbContext.UserProfiles.Include(prof => prof.User).Where(x => x.User.Id == userId).FirstOrDefaultAsync(); if (profileModel == null) { var errorResp = new UserProfileResponse { Succes = false, Errors = new List <string>() }; errorResp.Errors.Add("User with such id does not exist!"); return(errorResp); } var newAvatarName = await _imageService.UploadImage(Enums.ImageTypeEnum.PROFILE_PICTURE, req); if (profileModel.ProfilePicturePath != "\\images\\avatars\\default.png") { _imageService.DeleteImage(profileModel.ProfilePicturePath); } profileModel.ProfilePicturePath = newAvatarName; _dbContext.Update(profileModel); _dbContext.SaveChanges(); var response = _mapper.Map <UserProfileResponse>(profileModel); return(response); }
public string Login(string mobile, string password) { string bllRsponse = string.Empty; AuthRequest auth = new AuthRequest(); UserRequest userRequest = new UserRequest(); bllRsponse = auth.Login(mobile, password); //bllRsponse = auth.Login("13012345676", "654321"); // 将接口返回的信息记录在服务端Sesson LoginResponse bllRsponseModel = new LoginResponse(); bllRsponseModel = JsonHelper.DeserializeJsonToObject <LoginResponse>(bllRsponse); if (bllRsponseModel.code == 0) { Session["Phone"] = mobile; Session["token"] = bllRsponseModel.data.token; Session["role"] = bllRsponseModel.data.role; UserProfileResponse userProfileResponse = userRequest.profile(bllRsponseModel.data.token, ""); Session["username"] = userProfileResponse.data.username; Session["hospitalid"] = userProfileResponse.data.hospitalid; Session["CurrentUserID"] = userProfileResponse.data.id; Session["CurrentUserHospitalID"] = userProfileResponse.data.hospitalid; Session["password"] = password; } ////返回接口对象 return(bllRsponse); }
public void Add_Returns_BadRequest_for_null_userProfile() { var uut = GetUut(); UserProfileResponse expected = new UserProfileResponse(HttpBadRequest); var actual = uut.Add(null).GetAwaiter().GetResult(); Assert.Equal(expected, actual); }
/// <summary> /// Gets the Groove profile of the currently logged-in user and updates the <see cref="UserHasGrooveSubscription"/> /// and <see cref="UserGrooveSubscriptionCountry"/> properties. /// </summary> private async Task UpdateUserSubscriptionInformationAsync() { UserProfileResponse profileResponse = await _grooveClient.GetUserProfileAsync(MediaNamespace.music); _errorViewModel.HandleGrooveApiError(profileResponse.Error); UserHasGrooveSubscription = profileResponse.HasSubscription ?? false; UserGrooveSubscriptionCountry = profileResponse.Subscription?.Region; }
private static void VerifyUserSettings(UserProfileRequest request, UserProfileResponse response) { Assert.NotNull(response); Assert.Equal(request.Email, response.Email); Assert.Equal(request.FirstName, response.FirstName); Assert.Equal(request.Language, response.Language); Assert.Equal(request.LastName, response.LastName); Assert.Equal(request.PhoneNumber, response.PhoneNumber); }
public void FakeUserProfileEndpoint(UserProfileRequest req, UserProfileResponse resp) { var producer = SVX.Channel.GenerateNew(SVX_Principal); var client = SVX.Channel.GenerateNew(SVX_Principal); messageStructures.userProfileRequest.FakeImport(req, producer, client); SVX.SVX_Ops.FakeCall(SVX_MakeUserProfileResponse, req, (AccessTokenParams)null, resp); messageStructures.userProfileResponse.FakeExportDirectResponse(resp, producer); }
private void GetEmployeeSpesificInfo(UserProfileResponse userResponse) { userResponse.AvailablityInfo = GetAvailabilityInfo((Guid)userResponse.Id); userResponse.EducationHistory = GetEducationHistory((Guid)userResponse.Id); userResponse.EmployementHistory = GetEmploymentHistory((Guid)userResponse.Id); userResponse.OtherDocs = GetEmployeeDocs((Guid)userResponse.Id); userResponse.Portfolio = GetEmployeePortFolio((Guid)userResponse.Id); userResponse.Skills = GetEmployeeSkillSet((Guid)userResponse.Id); }
public ActionResult <UserProfileResponse> GetUserProfile() { var profile = new UserProfileResponse { IsVhOfficerAdministratorRole = User.IsInRole(AppRoles.VhOfficerRole), IsCaseAdministrator = User.IsInRole(AppRoles.CaseAdminRole) }; return(Ok(profile)); }
private UserProfileResponse GenerateUserProfileResponse(User user) { var response = new UserProfileResponse() { Id = user.Id, DisplayName = user.DisplayName }; return(response); }
public UserService(IUserRepository userRepository, IMapper mapper, ILogger <UserService> logger) { _userRepository = userRepository; _mapper = mapper; _logger = logger; _response = new MainResponse(); _uploadImage = new UploadImage(); _userProfileResponse = new UserProfileResponse(); _response.Status = false; _userResponse = new MainUserResponse(); }
public static UserProfileResponse MapUserToResponseModel(ClaimsPrincipal user) { var response = new UserProfileResponse { Username = user.Identity?.Name?.ToLower().Trim() }; var roleClaims = user.Claims.Where(c => c.Type == ClaimTypes.Role).ToList(); response.Role = DetermineRoleFromClaims(roleClaims); return(response); }
public async Task <AuthenticationResult> RegisterUserAsync(string email, string password) { var existingUser = await _userManager.FindByEmailAsync(email); if (existingUser != null) { return(new AuthenticationResult { Errors = new[] { "User with this email address already exists" } }); } var newUser = new IdentityUser { Email = email, UserName = email }; var createdUser = await _userManager.CreateAsync(newUser, password); if (!createdUser.Succeeded) { return(new AuthenticationResult { Errors = createdUser.Errors.Select(x => x.Description) }); } DateTime createdDate; createdDate = DateTime.Today; var userProfile = new UserProfile { FirstName = null, LastName = null, Email = email, Address = null, ProfilePicture = null, DOB = null, DateCreated = createdDate }; await _userProfileService.CreateProfileAsync(userProfile); var profileId = new UserProfileResponse { Id = userProfile.Id }; userProfileId = profileId.Id.ToString(); return(await GenerateAuthenticationResultForUserAsync(newUser)); }
private async Task <ErrorBase> Follow(UserProfileResponse userProfileResponse, CancellationToken ct) { var request = new FollowModel(User.UserInfo, userProfileResponse.HasFollowed ? FollowType.UnFollow : FollowType.Follow, UserName); var response = await Api.Follow(request, ct); if (response.IsSuccess) { userProfileResponse.HasFollowed = !userProfileResponse.HasFollowed; } return(response.Error); }
public async Task <UserProfileResponse> Add(UserProfile?userProfile, UserAuthentication?userAuthentication) { UserProfileResponse errorResponse = new UserProfileResponse(HttpInternalServerError); if (userProfile == null) { return(errorResponse); } var userProfileDto = _profileMapper.Map <UserProfileDto>(userProfile); var userAuthenticationDto = _authenticationMapper.Map <UserAuthenticationDto>(userAuthentication); using IDbConnection connection = GetConnection(); int? id; IDbTransaction transaction; using var dbTransaction = transaction = connection.BeginTransaction(); try { id = await connection.InsertAsync(userProfileDto, transaction); if (id != null) { userAuthenticationDto.UserId = id; await connection.InsertAsync(userAuthenticationDto, transaction); } transaction.Commit(); } catch (Exception e) { transaction.Rollback(); if (e.Message.Contains(userNameUniqueConstraint)) { _logger.Debug(e, "failed to add user profile: {Profile}. Username duplicate", userProfile); return(new UserProfileResponse(HttpBadRequest, "Username already in use")); } _logger.Error(e, "failed to add user profile: {Profile}", userProfile); return(errorResponse); } if (id == null) { return(errorResponse); } var profile = await GetById(id.Value); if (profile == null) { return(errorResponse); } profile.Id = id; return(new UserProfileResponse(HttpOk, profile)); }
/// <summary>Checks if user has a specified privilege.</summary> /// <param name="context">Context of the command execution.</param> /// <param name="userID">ID of the user.</param> /// <param name="privileges">Required privileges flags.</param> /// <param name="cancellationToken">Cancellation token for cancelling the task.</param> /// <returns>True if user has at least one of specified privileges; otherwise false.</returns> public static async Task <bool> CheckPrivilegeAsync(ICommandContext context, uint userID, WolfPrivilege privileges, CancellationToken cancellationToken = default) { UserProfileResponse response = await context.Client.SendAsync <UserProfileResponse>( new UserProfileMessage(new uint[] { userID }, true, true), cancellationToken).ConfigureAwait(false); WolfUser user = response?.UserProfiles?.FirstOrDefault(u => u.ID == userID); if (user == null) { return(false); } return((privileges & user.Privileges) != 0); }
private async Task <Exception> Follow(UserProfileResponse userProfileResponse, CancellationToken ct) { var hasFollowed = userProfileResponse.HasFollowed; var request = new FollowModel(AppSettings.User.UserInfo, hasFollowed ? FollowType.UnFollow : FollowType.Follow, UserName); var response = await Api.Follow(request, ct); if (response.IsSuccess) { userProfileResponse.HasFollowed = !hasFollowed; } return(response.Exception); }
public static UserProfileResponse MapUserToResponseModel(ClaimsPrincipal user) { var response = new UserProfileResponse { FirstName = user.Claims.First(c => c.Type == ClaimTypes.GivenName).Value, LastName = user.Claims.First(c => c.Type == ClaimTypes.Surname).Value, DisplayName = user.Claims.First(c => c.Type == "name").Value, Username = user.Identity?.Name?.ToLower().Trim(), }; var roleClaims = user.Claims.Where(c => c.Type == ClaimTypes.Role).ToList(); response.Role = DetermineRoleFromClaims(roleClaims); return(response); }
public IActionResult Create([FromBody] UserProfile Profile) { UserProfileResponse _reponse = _applicationProfileService.CreateProfile(Profile); if (_reponse.Success == true) { return(Ok(_reponse)); } else { return(BadRequest(_reponse.Message)); } }