Beispiel #1
0
        /// <summary>
        /// Atualiza um usuário.
        /// </summary>
        /// <param name="newUserRequest"></param>
        /// <returns>Token de autenticação em caso de sucesso.</returns>
        public static AuthResult UpdateUser(NewRequest newUserRequest)
        {
            AuthResult authResult = ValidateRequest(newUserRequest, true);

            if (authResult.AuthStatus == AuthStatus.OK)
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    UserAccountEntity user = AccountRepository.Instance.FindByUserName(newUserRequest.Username);

                    if (!String.IsNullOrWhiteSpace(newUserRequest.Password))
                    {
                        var security = PasswordUtils.CreateHash(newUserRequest.Password);
                        user.PasswordHash  = security.Item2;
                        user.SecurityStamp = security.Item1;
                    }
                    else
                    {
                        user.PasswordHash  = user.PasswordHash;
                        user.SecurityStamp = user.SecurityStamp;
                    }

                    if (!String.IsNullOrWhiteSpace(newUserRequest.Email))
                    {
                        user.UserName = newUserRequest.Email;
                    }

                    AccountRepository.Instance.Update(user);

                    scope.Complete();
                }
            }

            return(authResult);
        }
Beispiel #2
0
        /// <summary>
        /// Altera a senha de um usuário
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="currentPwd"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public static AuthResult ChangePassword(int userId, string currentPwd, string newPwd)
        {
            AuthResult authResult = new AuthResult();

            UserAccountEntity user = AccountRepository.Instance.GetById(userId);

            if (user == null)
            {
                authResult.AuthStatus = AuthStatus.USER_NOT_EXISTS;
                return(authResult);
            }

            //Valida senha
            bool isValidPassword = PasswordUtils.ValidatePassword(currentPwd, user.SecurityStamp, user.PasswordHash);

            //Senha inválida
            if (!isValidPassword)
            {
                authResult.AuthStatus = AuthStatus.INVALID_CREDENTIALS;
                return(authResult);
            }

            var security = PasswordUtils.CreateHash(newPwd);

            user.PasswordHash  = security.Item2;
            user.SecurityStamp = security.Item1;

            AccountRepository.Instance.Update(user);

            authResult.UserRoles = AccountRepository.Instance.GetUserRoles(user.Id);


            return(authResult);
        }
Beispiel #3
0
        public async Task <FriendTokenEntity> GetFriendLink(UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var theAuthClient = new HttpClient();
                var param         = new Dictionary <String, String> {
                    { "type", "ONE" }
                };
                var jsonObject    = JsonConvert.SerializeObject(param);
                var stringContent = new StringContent(jsonObject, Encoding.UTF8, "application/json");
                var request       = new HttpRequestMessage(HttpMethod.Post, UrlConstants.FriendMeUrl)
                {
                    Content = stringContent
                };
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                var response = await theAuthClient.SendAsync(request);

                string responseContent = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <FriendTokenEntity>(responseContent));;
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public async Task <SessionInviteEntity> GetSessionInvites(int offset, UserAccountEntity userAccountEntity)
        {
            try
            {
                var authenticationManager = new AuthenticationManager();
                var user = userAccountEntity.GetUserEntity();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                string url = string.Format("https://{0}-ivt.np.community.playstation.net/sessionInvitation/v1/users/{1}/invitations?fields=@default,sessionId,receivedDate,expired,updateDate,fromUser,subject,npTitleDetail,availablePlatforms&npLanguage={2}&offset={3}", user.Region, user.OnlineId, user.Language, offset);
                // TODO: Fix this cheap hack to get around caching issue. For some reason, no-cache is not working...
                url += "&r=" + Guid.NewGuid();
                var theAuthClient = new HttpClient();
                var request       = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                request.Headers.CacheControl  = new CacheControlHeaderValue {
                    NoCache = true
                };
                var response = await theAuthClient.SendAsync(request);

                var responseContent = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseContent))
                {
                    return(null);
                }
                var sessionInvite = JsonConvert.DeserializeObject <SessionInviteEntity>(responseContent);
                return(sessionInvite);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #5
0
        /// <summary>
        /// identify logon user
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        internal bool IdentifyLogonUser(LoginUser loginUser, UserAccountEntity account)
        {
            var isPwdMachted = (account != null &&
                                Validate(account, loginUser.Password));

            return(isPwdMachted);
        }
Beispiel #6
0
        public async Task <TrophyEntity> GetTrophyList(string user, int offset, UserAccountEntity userAccountEntity)
        {
            try
            {
                var authenticationManager = new AuthenticationManager();
                var userAccount           = userAccountEntity.GetUserEntity();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                string url = string.Format("https://{0}-tpy.np.community.playstation.net/trophy/v1/trophyTitles?fields=%40default&npLanguage={1}&iconSize=s&platform=PS3%2CPSVITA%2CPS4&offset={2}&limit=64&comparedUser={3}&fromUser={4}", userAccount.Region, userAccount.Language, offset, user, userAccountEntity.GetUserEntity().OnlineId);
                // TODO: Fix this cheap hack to get around caching issue. For some reason, no-cache is not working...
                url += "&r=" + Guid.NewGuid();
                var theAuthClient = new HttpClient();
                var request       = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                request.Headers.CacheControl  = new CacheControlHeaderValue {
                    NoCache = true
                };
                HttpResponseMessage response = await theAuthClient.SendAsync(request);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseContent))
                {
                    return(null);
                }
                var trophy = JsonConvert.DeserializeObject <TrophyEntity>(responseContent);
                return(trophy);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #7
0
        public async Task <NotificationEntity> GetNotifications(string username, UserAccountEntity userAccountEntity)
        {
            try
            {
                var authenticationManager = new AuthenticationManager();
                var user = userAccountEntity.GetUserEntity();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                string url           = string.Format("https://{0}-ntl.np.community.playstation.net/notificationList/v1/users/{1}/notifications?fields=@default%2Cmessage%2CactionUrl&npLanguage={2}", user.Region, username, user.Language);
                var    theAuthClient = new HttpClient();
                // TODO: Fix this cheap hack to get around caching issue. For some reason, no-cache is not working...
                url += "&r=" + Guid.NewGuid();
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                request.Headers.CacheControl  = new CacheControlHeaderValue {
                    NoCache = true
                };
                HttpResponseMessage response = await theAuthClient.SendAsync(request);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseContent))
                {
                    return(null);
                }
                var notification = JsonConvert.DeserializeObject <NotificationEntity>(responseContent);
                return(notification);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #8
0
        public async Task <NicoNicoEntity> GetNicoFeed(string status, string platform, int offset, int limit, string sort,
                                                       UserAccountEntity userAccountEntity)
        {
            try
            {
                var url = EndPoints.NicoNicoBaseUrl;
                // Sony's app hardcodes this value to 0.
                // This app could, in theory, allow for more polling of data, so these options are left open to new values and limits.
                url += string.Format("offset={0}&", offset);
                url += string.Format("limit={0}&", limit);
                url += string.Format("status={0}&", status);
                url += string.Format("sce_platform={0}&", platform);
                url += string.Format("sort={0}", sort);
                // TODO: Fix this cheap hack to get around caching issue. For some reason, no-cache is not working...
                url += "&r=" + Guid.NewGuid();
                var result = await _webManager.GetData(new Uri(url), userAccountEntity);

                var nico = JsonConvert.DeserializeObject <NicoNicoEntity>(result.ResultJson);
                return(nico);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to get Nico Nico Douga feed", ex);
            }
        }
        public async Task RefreshAccessToken(UserAccountEntity account)
        {
            try
            {
                var dic = new Dictionary <String, String>();
                dic["grant_type"]    = "refresh_token";
                dic["client_id"]     = EndPoints.ConsumerKey;
                dic["client_secret"] = EndPoints.ConsumerSecret;
                dic["refresh_token"] = account.GetRefreshToken();
                dic["scope"]         = "psn:sceapp";

                account.SetAccessToken("updating", null);
                account.SetRefreshTime(1000);
                var         theAuthClient = new HttpClient();
                HttpContent header        = new FormUrlEncodedContent(dic);
                var         response      = await theAuthClient.PostAsync(EndPoints.OauthToken, header);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();

                    var o = JObject.Parse(responseContent);
                    if (string.IsNullOrEmpty(responseContent))
                    {
                        throw new RefreshTokenException("Could not refresh the user token, no response data");
                    }
                    account.SetAccessToken((String)o["access_token"], (String)o["refresh_token"]);
                    account.SetRefreshTime(long.Parse((String)o["expires_in"]));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Could not refresh the user token", ex);
            }
        }
Beispiel #10
0
        public async Task <Result> DeleteData(Uri uri, StringContent json, UserAccountEntity userAccountEntity)
        {
            var httpClient = new HttpClient();

            try
            {
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var user = userAccountEntity.GetUserEntity();
                if (user != null)
                {
                    var language = userAccountEntity.GetUserEntity().Language;
                    httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
                }
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                var response = await httpClient.DeleteAsync(uri);

                var responseContent = await response.Content.ReadAsStringAsync();

                return(response.IsSuccessStatusCode ? new Result(true, string.Empty) : new Result(false, responseContent));
            }
            catch (Exception)
            {
                return(new Result(false, string.Empty));
            }
        }
Beispiel #11
0
        private void saveUserAccount(DataListItem dli)
        {
            HiddenField       hdnAccountId = dli.FindControl("hdnAccountId") as HiddenField;
            int               acctId       = Convert.ToInt32(hdnAccountId.Value);
            AccountEntity     acct         = new AccountEntity(acctId);
            UserAccountEntity uae          = new UserAccountEntity();

            if (_userAccounts.Where(x => x.AccountId == acct.AccountId).Count() > 0)
            {
                uae = _userAccounts.Where(x => x.AccountId == acct.AccountId).First();
            }

            CheckBox chkAccount = dli.FindControl("chkAccount") as CheckBox;

            if (chkAccount.Checked)
            {
                if (uae.IsNew)
                {
                    uae.UserId    = _user.UserId;
                    uae.AccountId = acct.AccountId;
                    uae.Save();
                }
            }
            else
            {
                if (!uae.IsNew)
                {
                    _userAccounts.Remove(uae);
                    uae.Delete();
                }
            }
        }
Beispiel #12
0
        public async Task <bool> CreatePost(string messageUserId, string post,
                                            UserAccountEntity userAccountEntity)
        {
            try
            {
                var          user        = userAccountEntity.GetUserEntity();
                var          url         = string.Format(EndPoints.CreatePost, user.Region, messageUserId);
                const string boundary    = "abcdefghijklmnopqrstuvwxyz";
                var          messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body           = post,
                        fakeMessageUid = 1384958573288,
                        messageKind    = 1
                    }
                };

                var json          = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                var form = new MultipartContent("mixed", boundary)
                {
                    stringContent
                };
                var result = await _webManager.PostData(new Uri(url), form, null, userAccountEntity);

                return(result.IsSuccess);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to send post", ex);
            }
        }
Beispiel #13
0
        public async Task <Result> GetData(Uri uri, UserAccountEntity userAccountEntity)
        {
            var httpClient = new HttpClient();

            try
            {
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var user = userAccountEntity.GetUserEntity();
                if (user != null)
                {
                    var language = userAccountEntity.GetUserEntity().Language;
                    httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
                }
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                var response = await httpClient.GetAsync(uri);

                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new WebException("PSN API Error: Service not found.");
                }
                var responseContent = await response.Content.ReadAsStringAsync();

                return(string.IsNullOrEmpty(responseContent) ? new Result(false, string.Empty) : new Result(true, responseContent));
            }
            catch
            {
                throw new WebException("PSN API Error: Service not found.");
            }
        }
Beispiel #14
0
        /// <summary>
        /// user register
        /// </summary>
        /// <param name="account"></param>
        public void Register(UserAccountEntity account)
        {
            //verify input validation
            var result     = ResponseResult.Default();
            var userEntity = QuickRepository.GetDefaultByName <UserAccountEntity>("LoginName", account.LoginName);

            if (userEntity != null)
            {
                throw new ApplicationException("用户名已经被占用,请重新存在!");
            }
            else if (string.IsNullOrEmpty(account.Password) || account.Password.Length < 6)
            {
                throw new ApplicationException("密码不能为空,或者长度不能小于6位!");
            }

            //create
            try
            {
                QuickRepository.Insert <UserAccountEntity>(account);
            }
            catch (System.Exception)
            {
                throw;
            }
        }
Beispiel #15
0
        public async static Task <UserEntity> GetUserAvatar(string userName, UserAccountEntity userAccountEntity)
        {
            try
            {
                var authenticationManager = new AuthenticationManager();
                var user = userAccountEntity.GetUserEntity();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                string url = string.Format("https://{0}-prof.np.community.playstation.net/userProfile/v1/users/{1}/profile?fields=avatarUrl", user.Region, userName);
                // TODO: Fix this cheap hack to get around caching issue. For some reason, no-cache is not working...
                url += "&r=" + Guid.NewGuid();
                var theAuthClient = new HttpClient();
                var request       = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                HttpResponseMessage response = await theAuthClient.SendAsync(request);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseContent))
                {
                    return(null);
                }
                var friend = JsonConvert.DeserializeObject <UserEntity>(responseContent);
                return(friend);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #16
0
 public async void ClearMessages(MessageEntity messageEntity, UserAccountEntity userAccountEntity)
 {
     try
     {
         var authenticationManager = new AuthenticationManager();
         var user = userAccountEntity.GetUserEntity();
         if (userAccountEntity.GetAccessToken().Equals("refresh"))
         {
             await authenticationManager.RefreshAccessToken(userAccountEntity);
         }
         var messageUids = new List <int>();
         messageUids.AddRange(messageEntity.messages.Where(o => o.seenFlag == false).Select(message => message.messageUid));
         if (messageUids.Count == 0)
         {
             return;
         }
         string url           = string.Format("https://{0}-gmsg.np.community.playstation.net/groupMessaging/v1/messageGroups/{1}/messages?messageUid={2}", user.Region, messageEntity.messageGroup.messageGroupId, string.Join(",", messageUids));
         var    theAuthClient = new HttpClient();
         var    request       = new HttpRequestMessage(HttpMethod.Put, url);
         request.Headers.CacheControl = new CacheControlHeaderValue {
             NoCache = true
         };
         request.Headers.Add("Origin", "http://psapp.dl.playstation.net");
         request.Headers.Add("Referer", "http://psapp.dl.playstation.net/psapp/6228351b09c436f44f1c53955c0a51ca/index.html");
         request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
         request.Content = new StringContent("{\"seenFlag\":true}", Encoding.UTF8, "application/json");
         await theAuthClient.SendAsync(request);
     }
     catch (Exception)
     {
         Debug.WriteLine("Failed to clear messages");
     }
 }
        public async Task <UserAccountEntity.User> GetUserEntity(UserAccountEntity userAccountEntity)
        {
            try
            {
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                string url           = "https://vl.api.np.km.playstation.net/vl/api/v1/mobile/users/me/info";
                var    theAuthClient = new HttpClient();
                var    request       = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                HttpResponseMessage response = await theAuthClient.SendAsync(request);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseContent))
                {
                    return(null);
                }
                UserAccountEntity.User user = UserAccountEntity.ParseUser(responseContent);
                return(user);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public async Task <bool> SendNameRequest(string username, UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var theAuthClient = new HttpClient();
                var param         = new Dictionary <String, String>();
                var url           = string.Format("https://{0}-prof.np.community.playstation.net/userProfile/v1/users/{1}/friendList/{2}/personalDetailSharing", user.Region, user.OnlineId, username);
                var request       = new HttpRequestMessage(HttpMethod.Post, url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                //string requestContent = await request.Content.ReadAsStringAsync();
                var response = await theAuthClient.SendAsync(request);

                return(response.IsSuccessStatusCode);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #19
0
        public async void SetMessages(string userName, UserAccountEntity userAccountEntity)
        {
            MessageGroupCollection = new ObservableCollection <MessageGroupItem>();
            var messageManager = new MessageManager();

            _messageEntity =
                await
                messageManager.GetGroupConversation(
                    string.Format("~{0},{1}", userName, App.UserAccountEntity.GetUserEntity().OnlineId),
                    App.UserAccountEntity);

            if (_messageEntity == null)
            {
                return;
            }
            foreach (
                MessageGroupItem newMessage in
                _messageEntity.messages.Select(message => new MessageGroupItem {
                Message = message
            }))
            {
                GetAvatar(newMessage, userAccountEntity);
                MessageGroupCollection.Add(newMessage);
            }
        }
        public async Task <string> GetRequestMessage(string username, UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var theAuthClient = new HttpClient();
                var url           = string.Format("https://{0}-prof.np.community.playstation.net/userProfile/v1/users/{1}/friendList/{2}/requestMessage", user.Region, user.OnlineId, username);
                var request       = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                var response = await theAuthClient.SendAsync(request);

                var responseContent = await response.Content.ReadAsStringAsync();

                var o = JObject.Parse(responseContent);
                return(o["requestMessage"] != null ? (string)o["requestMessage"] : string.Empty);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #21
0
        public async Task <bool> ClearMessages(MessageEntity messageEntity, UserAccountEntity userAccountEntity)
        {
            try
            {
                if (messageEntity.messages == null)
                {
                    return(false);
                }
                var user        = userAccountEntity.GetUserEntity();
                var messageUids = new List <long>();
                messageUids.AddRange(messageEntity.messages.Where(o => o.seenFlag == false).Select(message => message.messageUid));
                if (messageUids.Count == 0)
                {
                    return(false);
                }
                var url    = string.Format(EndPoints.ClearMessages, user.Region, messageEntity.messageGroup.messageGroupId, string.Join(",", messageUids));
                var json   = new StringContent("{\"seenFlag\":true}", Encoding.UTF8, "application/json");
                var result = await _webManager.PutData(new Uri(url), json, userAccountEntity);

                return(result.IsSuccess);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to clear messages", ex);
            }
        }
Beispiel #22
0
        public async Task <Stream> GetImageMessageContent(string id, MessageEntity.Message message,
                                                          UserAccountEntity userAccountEntity)
        {
            try
            {
                var          user    = userAccountEntity.GetUserEntity();
                const string content = "image-data-0";
                var          url     = string.Format(EndPoints.MessageContent, user.Region, id, message.messageUid, content, user.Language);
                url += "&r=" + Guid.NewGuid();
                var theAuthClient = new HttpClient();
                var request       = new HttpRequestMessage(HttpMethod.Get, url);
                request.Headers.CacheControl = new CacheControlHeaderValue {
                    NoCache = true
                };
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                var response = await theAuthClient.SendAsync(request);

                var responseContent = await response.Content.ReadAsStreamAsync();

                return(responseContent);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to get image message content", ex);
            }
        }
Beispiel #23
0
        /// <summary>
        /// change user password
        /// </summary>
        /// <param name="oldPassword">old password</param>
        /// <param name="newPassword">new password</param>
        public void ChangePassword(string loginName, string oldPassword, string newPassword)
        {
            UserAccountEntity userEntity = null;

            try
            {
                userEntity = QuickRepository.GetDefaultByName <UserAccountEntity>("LoginName", loginName);
                var isChecked = CheckPassword(userEntity, oldPassword);     //it's better to limit wrong password 3 or 6 times to prevent someone crack the account
                if (!isChecked)
                {
                    throw new ApplicationException("用户名和密码不匹配,请重试.");
                }
            }
            catch (System.ApplicationException ex)
            {
                throw new ApplicationException("修改密码发生错误!");
            }

            try
            {
                var saltText = string.Empty;
                EnumHashProvider hashProvider;
                var encryptedPwd = HashingAlgorithmUtility.GetEncryptedHashText(newPassword, out saltText, out hashProvider);

                userEntity.Password       = encryptedPwd;
                userEntity.PasswordFormat = (short)hashProvider;
                userEntity.PasswordSalt   = saltText;

                QuickRepository.Update <UserAccountEntity>(userEntity);
            }
            catch (System.ApplicationException ex)
            {
                throw;
            }
        }
Beispiel #24
0
        private async void GetAvatar(MessageGroupItem message, UserAccountEntity userAccountEntity)
        {
            UserEntity user = await UserManager.GetUserAvatar(message.Message.senderOnlineId, userAccountEntity);

            message.AvatarUrl = user.AvatarUrl;
            OnPropertyChanged("MessageGroupCollection");
        }
Beispiel #25
0
        /// <summary>
        /// check user password
        /// </summary>
        /// <param name="userName">user name</param>
        /// <param name="password">password</param>
        /// <returns></returns>
        public bool CheckPassword(UserAccountEntity user, string password)
        {
            var isChecked = HashingAlgorithmUtility.CompareHash(user.PasswordFormat,
                                                                password, user.PasswordSalt, user.Password);

            return(isChecked);
        }
Beispiel #26
0
        public static async Task <bool> ClearNotification(NotificationEntity.Notification notification,
                                                          UserAccountEntity userAccountEntity)
        {
            try
            {
                var authenticationManager = new AuthenticationManager();
                var user = userAccountEntity.GetUserEntity();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                string url           = string.Format("https://{0}-ntl.np.community.playstation.net/notificationList/v1/users/{1}/notifications/{2}/{3}", user.Region, user.OnlineId, notification.NotificationGroup, notification.NotificationId);
                var    theAuthClient = new HttpClient();
                var    request       = new HttpRequestMessage(HttpMethod.Put, url)
                {
                    Content = new StringContent("{\"seenFlag\":true}", Encoding.UTF8, "application/json")
                };
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                request.Headers.CacheControl  = new CacheControlHeaderValue {
                    NoCache = true
                };
                HttpResponseMessage response = await theAuthClient.SendAsync(request);

                return(response.IsSuccessStatusCode);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #27
0
        private async void GetAvatar(SessionInviteMember member, UserAccountEntity userAccountEntity)
        {
            UserEntity user = await UserManager.GetUserAvatar(member.Member.OnlineId, userAccountEntity);

            member.AvatarUrl = user.AvatarUrl;
            OnPropertyChanged("SessionInviteMembers");
        }
        public async Task <UserAccountEntity.User> GetUserEntity(UserAccountEntity userAccountEntity)
        {
            try
            {
                var authenticationManager = new AuthenticationManager();
                if (userAccountEntity.GetAccessToken().Equals("refresh"))
                {
                    await authenticationManager.RefreshAccessToken(userAccountEntity);
                }
                var theAuthClient = new HttpClient();
                var request       = new HttpRequestMessage(HttpMethod.Get, UrlConstants.VerifyUser);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
                HttpResponseMessage response = await theAuthClient.SendAsync(request);

                string responseContent = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(responseContent))
                {
                    return(null);
                }
                UserAccountEntity.User user = UserAccountEntity.ParseUser(responseContent);
                return(user);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #29
0
        /// <summary>
        /// Reseta a senha de um usuário
        /// </summary>
        /// <param name="ResetPwdRequest"></param>
        /// <returns>Token de autenticação em caso de sucesso.</returns>
        public static AuthResult ResetPassword(LoginRequest ResetPwdRequest)
        {
            AuthResult authResult = new AuthResult();

            try
            {
                UserAccountEntity user = AccountRepository.Instance.FindByUserName(ResetPwdRequest.UserName != null ? ResetPwdRequest.UserName.ToLower() : null);

                if (user == null)
                {
                    authResult.AuthStatus = AuthStatus.USER_NOT_EXISTS;
                    return(authResult);
                }

                UserProfileEntity profile = AccountRepository.Instance.GetProfileById(user.Id);

                if (profile == null)
                {
                    authResult.AuthStatus = AuthStatus.USER_NOT_EXISTS;
                    return(authResult);
                }

                Random rnd = new Random();

                string newPwd = rnd.Next().ToString(); //"PWD" + rnd.Next();

                NewRequest request = new NewRequest();

                request.Email    = user.UserName;
                request.Username = user.UserName;
                request.Password = newPwd;

                UpdateUser(request);

                string EmailBody = "Olá! sua nova senha para acessar a plataforma do Gamific é: " + newPwd;

                string EmailTo = ParameterCache.Get("RESET_PASSWORD_EMAIL");

                var result = EmailDispatcher.SendEmail(EmailTo, "Nova Senha Gamific", new List <string>()
                {
                    user.UserName
                }, EmailBody);

                if (result)
                {
                    authResult.AuthStatus = AuthStatus.OK;
                }
                else
                {
                    authResult.AuthStatus = AuthStatus.ERROR;
                }
            }
            catch (Exception ex)
            {
                authResult.AuthStatus = AuthStatus.ERROR;
            }

            return(authResult);
        }
        private async Task <bool> LoginTest()
        {
            UserAccountEntity = new UserAccountEntity();
            var authManager       = new AuthenticationManager();
            var userAccountEntity = new UserAccountEntity();

            return(await authManager.RefreshAccessToken(UserAccountEntity));
        }