chore: 重构 AVUser 模块

oneRain 2019-08-21 16:30:34 +08:00
parent fc4ff081f7
commit c303a5d307
9 changed files with 179 additions and 308 deletions

View File

@ -28,9 +28,47 @@ namespace LeanCloudTests {
} }
[Test] [Test]
public async Task Login() { public async Task LoginWithUsername() {
AVUser user = await AVUser.LogInAsync("hello", "world"); AVUser user = await AVUser.LogInAsync("hello", "111111");
TestContext.Out.WriteLine($"{user.ObjectId} login"); TestContext.Out.WriteLine($"{user.ObjectId}, {user.SessionToken} login");
}
[Test]
public async Task LoginWithEmail() {
AVUser user = await AVUser.LogInByEmailAsync("111111@qq.com", "111111");
Assert.AreEqual(user, AVUser.CurrentUser);
TestContext.Out.WriteLine($"{AVUser.CurrentUser.SessionToken} login");
}
[Test]
public async Task Become() {
AVUser user = await AVUser.BecomeAsync("36idbfnt8hlmdo4rki0f5hevq");
Assert.AreEqual(user, AVUser.CurrentUser);
TestContext.Out.WriteLine($"{AVUser.CurrentUser.SessionToken} login");
}
[Test]
public async Task IsAuthenticated() {
AVUser user = await AVUser.LogInByEmailAsync("111111@qq.com", "111111");
Assert.IsTrue(user.IsCurrent);
Assert.AreEqual(user, AVUser.CurrentUser);
bool authenticated = await user.IsAuthenticatedAsync();
Assert.IsTrue(authenticated);
}
[Test]
public async Task RefreshSessionToken() {
AVUser user = await AVUser.LogInByEmailAsync("111111@qq.com", "111111");
Assert.IsTrue(user.IsCurrent);
await user.RefreshSessionTokenAsync();
TestContext.Out.WriteLine(user.SessionToken);
}
[Test]
public async Task UpdatePassword() {
AVUser user = await AVUser.LogInAsync("111111", "111111");
await user.UpdatePasswordAsync("111111", "222222");
await user.UpdatePasswordAsync("222222", "111111");
} }
} }
} }

View File

@ -1,17 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Text;
using LeanCloud.Storage.Internal;
using System.Linq;
using System.Net.Http; using System.Net.Http;
namespace LeanCloud.Storage.Internal namespace LeanCloud.Storage.Internal {
{
/// <summary>
/// AVCommand is an <see cref="HttpRequest"/> with pre-populated
/// headers.
/// </summary>
public class AVCommand { public class AVCommand {
// 不同服务对应的服务器地址不同 // 不同服务对应的服务器地址不同
public virtual string Server => AVClient.CurrentConfiguration.ApiServer; public virtual string Server => AVClient.CurrentConfiguration.ApiServer;
@ -25,21 +16,14 @@ namespace LeanCloud.Storage.Internal
} }
public Dictionary<string, string> Headers { public Dictionary<string, string> Headers {
get { get; set;
if (AVUser.CurrentUser != null) {
return new Dictionary<string, string> {
{ "X-LC-Session", AVUser.CurrentUser.SessionToken }
};
}
return null;
}
} }
public object Content { public object Content {
get; set; get; set;
} }
public Uri Uri { internal Uri Uri {
get { get {
return new Uri($"{Server}/{AVClient.APIVersion}/{Path}"); return new Uri($"{Server}/{AVClient.APIVersion}/{Path}");
} }

View File

@ -65,6 +65,10 @@ namespace LeanCloud.Storage.Internal {
request.Headers.Add(header.Key, header.Value); request.Headers.Add(header.Key, header.Value);
} }
} }
// Session Token
if (AVUser.CurrentUser != null && !string.IsNullOrEmpty(AVUser.CurrentUser.SessionToken)) {
request.Headers.Add("X-LC-Session", AVUser.CurrentUser.SessionToken);
}
PrintRequest(httpClient, request, content); PrintRequest(httpClient, request, content);
var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

View File

@ -52,7 +52,6 @@ namespace LeanCloud.Storage.Internal {
} }
internal Task<Tuple<HttpStatusCode, IDictionary<string, object>>> GetFileToken(FileState fileState, CancellationToken cancellationToken) { internal Task<Tuple<HttpStatusCode, IDictionary<string, object>>> GetFileToken(FileState fileState, CancellationToken cancellationToken) {
string currentSessionToken = AVUser.CurrentSessionToken;
string str = fileState.Name; string str = fileState.Name;
IDictionary<string, object> parameters = new Dictionary<string, object>(); IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("name", str); parameters.Add("name", str);

View File

@ -108,7 +108,6 @@ namespace LeanCloud.Storage.Internal {
return key; return key;
} }
internal Task<Tuple<HttpStatusCode, IDictionary<string, object>>> GetQiniuToken(FileState state, CancellationToken cancellationToken) { internal Task<Tuple<HttpStatusCode, IDictionary<string, object>>> GetQiniuToken(FileState state, CancellationToken cancellationToken) {
string currentSessionToken = AVUser.CurrentSessionToken;
string str = state.Name; string str = state.Name;
IDictionary<string, object> parameters = new Dictionary<string, object>(); IDictionary<string, object> parameters = new Dictionary<string, object>();

View File

@ -20,7 +20,7 @@ namespace LeanCloud.Storage.Internal {
return serverState; return serverState;
} }
public async Task<IObjectState> LogInAsync(string username, string email, string password, CancellationToken cancellationToken) { public async Task<IObjectState> LogInAsync(string username, string email, string password) {
var data = new Dictionary<string, object>{ var data = new Dictionary<string, object>{
{ "password", password} { "password", password}
}; };
@ -35,7 +35,7 @@ namespace LeanCloud.Storage.Internal {
Method = HttpMethod.Post, Method = HttpMethod.Post,
Content = data Content = data
}; };
var ret = await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command, cancellationToken); var ret = await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
var serverState = AVObjectCoder.Instance.Decode(ret.Item2, AVDecoder.Instance); var serverState = AVObjectCoder.Instance.Decode(ret.Item2, AVDecoder.Instance);
serverState = serverState.MutatedClone(mutableClone => { serverState = serverState.MutatedClone(mutableClone => {
mutableClone.IsNew = ret.Item1 == System.Net.HttpStatusCode.Created; mutableClone.IsNew = ret.Item1 == System.Net.HttpStatusCode.Created;
@ -63,16 +63,19 @@ namespace LeanCloud.Storage.Internal {
return serverState; return serverState;
} }
public async Task<IObjectState> GetUserAsync(string sessionToken, CancellationToken cancellationToken) { public async Task<IObjectState> GetUserAsync(string sessionToken) {
var command = new AVCommand { var command = new AVCommand {
Path = "users/me", Path = "users/me",
Method = HttpMethod.Get Method = HttpMethod.Get,
Headers = new Dictionary<string, string> {
{ "X-LC-Session", sessionToken }
}
}; };
var ret = await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command, cancellationToken); var ret = await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
return AVObjectCoder.Instance.Decode(ret.Item2, AVDecoder.Instance); return AVObjectCoder.Instance.Decode(ret.Item2, AVDecoder.Instance);
} }
public async Task RequestPasswordResetAsync(string email, CancellationToken cancellationToken) { public async Task RequestPasswordResetAsync(string email) {
var command = new AVCommand { var command = new AVCommand {
Path = "requestPasswordReset", Path = "requestPasswordReset",
Method = HttpMethod.Post, Method = HttpMethod.Post,
@ -80,16 +83,16 @@ namespace LeanCloud.Storage.Internal {
{ "email", email} { "email", email}
} }
}; };
await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command, cancellationToken); await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
} }
public async Task<IObjectState> LogInWithParametersAsync(string relativeUrl, IDictionary<string, object> data, CancellationToken cancellationToken) { public async Task<IObjectState> LogInWithParametersAsync(string relativeUrl, IDictionary<string, object> data) {
var command = new AVCommand { var command = new AVCommand {
Path = relativeUrl, Path = relativeUrl,
Method = HttpMethod.Post, Method = HttpMethod.Post,
Content = data Content = data
}; };
var ret = await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command, cancellationToken); var ret = await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
var serverState = AVObjectCoder.Instance.Decode(ret.Item2, AVDecoder.Instance); var serverState = AVObjectCoder.Instance.Decode(ret.Item2, AVDecoder.Instance);
serverState = serverState.MutatedClone(mutableClone => { serverState = serverState.MutatedClone(mutableClone => {
mutableClone.IsNew = ret.Item1 == System.Net.HttpStatusCode.Created; mutableClone.IsNew = ret.Item1 == System.Net.HttpStatusCode.Created;
@ -97,7 +100,7 @@ namespace LeanCloud.Storage.Internal {
return serverState; return serverState;
} }
public async Task UpdatePasswordAsync(string userId, string sessionToken, string oldPassword, string newPassword, CancellationToken cancellationToken) { public async Task<IObjectState> UpdatePasswordAsync(string userId, string oldPassword, string newPassword) {
var command = new AVCommand { var command = new AVCommand {
Path = $"users/{userId}/updatePassword", Path = $"users/{userId}/updatePassword",
Method = HttpMethod.Put, Method = HttpMethod.Put,
@ -106,10 +109,11 @@ namespace LeanCloud.Storage.Internal {
{ "new_password", newPassword }, { "new_password", newPassword },
} }
}; };
await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command, cancellationToken); var ret = await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
return AVObjectCoder.Instance.Decode(ret.Item2, AVDecoder.Instance);
} }
public async Task<IObjectState> RefreshSessionTokenAsync(string userId, string sessionToken, CancellationToken cancellationToken) { public async Task<IObjectState> RefreshSessionTokenAsync(string userId) {
var command = new AVCommand { var command = new AVCommand {
Path = $"users/{userId}/refreshSessionToken", Path = $"users/{userId}/refreshSessionToken",
Method = HttpMethod.Put Method = HttpMethod.Put

View File

@ -337,7 +337,7 @@ namespace LeanCloud
return this.SaveExternal(); return this.SaveExternal();
return taskQueue.Enqueue( return taskQueue.Enqueue(
toAwait => FileController.SaveAsync(state, dataStream, AVUser.CurrentSessionToken, progress, cancellationToken), cancellationToken) toAwait => FileController.SaveAsync(state, dataStream, AVUser.CurrentUser.SessionToken, progress, cancellationToken), cancellationToken)
.OnSuccess(t => .OnSuccess(t =>
{ {
state = t.Result; state = t.Result;
@ -641,7 +641,7 @@ namespace LeanCloud
/// </remarks> /// </remarks>
public static Task<AVFile> GetFileWithObjectIdAsync(string objectId, CancellationToken cancellationToken) public static Task<AVFile> GetFileWithObjectIdAsync(string objectId, CancellationToken cancellationToken)
{ {
string currentSessionToken = AVUser.CurrentSessionToken; string currentSessionToken = AVUser.CurrentUser.SessionToken;
return FileController.GetAsync(objectId, currentSessionToken, cancellationToken).OnSuccess(_ => return FileController.GetAsync(objectId, currentSessionToken, cancellationToken).OnSuccess(_ =>
{ {
var filestate = _.Result; var filestate = _.Result;
@ -717,7 +717,7 @@ namespace LeanCloud
return Task.FromResult(0); return Task.FromResult(0);
} }
string sessionToken = AVUser.CurrentSessionToken; string sessionToken = AVUser.CurrentUser.SessionToken;
return toAwait.OnSuccess(_ => return toAwait.OnSuccess(_ =>
{ {

View File

@ -570,7 +570,7 @@ string propertyName
// Get the JSON representation of the object. // Get the JSON representation of the object.
currentOperations = StartSave(); currentOperations = StartSave();
sessionToken = AVUser.CurrentSessionToken; sessionToken = AVUser.CurrentUser.SessionToken;
deepSaveTask = DeepSaveAsync(estimatedData, sessionToken, cancellationToken); deepSaveTask = DeepSaveAsync(estimatedData, sessionToken, cancellationToken);
} }
@ -621,7 +621,7 @@ string propertyName
queryString = new Dictionary<string, object>(); queryString = new Dictionary<string, object>();
} }
return ObjectController.FetchAsync(state, queryString, AVUser.CurrentSessionToken, cancellationToken); return ObjectController.FetchAsync(state, queryString, AVUser.CurrentUser.SessionToken, cancellationToken);
}).Unwrap().OnSuccess(t => { }).Unwrap().OnSuccess(t => {
HandleFetchResult(t.Result); HandleFetchResult(t.Result);
return this; return this;
@ -709,7 +709,7 @@ string propertyName
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
public static Task SaveAllAsync<T>( public static Task SaveAllAsync<T>(
IEnumerable<T> objects, CancellationToken cancellationToken) where T : AVObject { IEnumerable<T> objects, CancellationToken cancellationToken) where T : AVObject {
return DeepSaveAsync(objects.ToList(), AVUser.CurrentSessionToken, cancellationToken); return DeepSaveAsync(objects.ToList(), AVUser.CurrentUser.SessionToken, cancellationToken);
} }
#endregion #endregion
@ -856,8 +856,8 @@ string propertyName
if (ObjectId == null) { if (ObjectId == null) {
return Task.FromResult(0); return Task.FromResult(0);
} }
string sessionToken = AVUser.CurrentSessionToken; string sessionToken = AVUser.CurrentUser.SessionToken;
return toAwait.OnSuccess(_ => { return toAwait.OnSuccess(_ => {
return ObjectController.DeleteAsync(State, sessionToken, cancellationToken); return ObjectController.DeleteAsync(State, sessionToken, cancellationToken);
@ -902,7 +902,7 @@ string propertyName
var states = uniqueObjects.Select(t => t.state).ToList(); var states = uniqueObjects.Select(t => t.state).ToList();
return toAwait.OnSuccess(_ => { return toAwait.OnSuccess(_ => {
var deleteTasks = ObjectController.DeleteAllAsync(states, var deleteTasks = ObjectController.DeleteAllAsync(states,
AVUser.CurrentSessionToken, AVUser.CurrentUser.SessionToken,
cancellationToken); cancellationToken);
return Task.WhenAll(deleteTasks); return Task.WhenAll(deleteTasks);

View File

@ -7,17 +7,13 @@ using System.Threading.Tasks;
namespace LeanCloud { namespace LeanCloud {
/// <summary> /// <summary>
/// Represents a user for a LeanCloud application. /// 用户类
/// </summary> /// </summary>
[AVClassName("_User")] [AVClassName("_User")]
public class AVUser : AVObject { public class AVUser : AVObject {
private static readonly IDictionary<string, IAVAuthenticationProvider> authProviders = private static readonly IDictionary<string, IAVAuthenticationProvider> authProviders =
new Dictionary<string, IAVAuthenticationProvider>(); new Dictionary<string, IAVAuthenticationProvider>();
private static readonly HashSet<string> readOnlyKeys = new HashSet<string> {
"sessionToken", "isNew"
};
internal static AVUserController UserController { internal static AVUserController UserController {
get { get {
return AVPlugins.Instance.UserController; return AVPlugins.Instance.UserController;
@ -25,20 +21,8 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// Whether the AVUser has been authenticated on this device. Only an authenticated /// 判断是否是当前用户
/// AVUser can be saved and deleted.
/// </summary> /// </summary>
[Obsolete("This property is deprecated, please use IsAuthenticatedAsync instead.")]
public bool IsAuthenticated {
get {
lock (mutex) {
return SessionToken != null &&
CurrentUser != null &&
CurrentUser.ObjectId == ObjectId;
}
}
}
public bool IsCurrent { public bool IsCurrent {
get { get {
return CurrentUser == this; return CurrentUser == this;
@ -46,34 +30,34 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// Whether the AVUser has been authenticated on this device, and the AVUser's session token is expired. /// 判断当前用户的 Session Token 是否有效
/// Only an authenticated AVUser can be saved and deleted.
/// </summary> /// </summary>
public Task IsAuthenticatedAsync() { /// <returns></returns>
public async Task<bool> IsAuthenticatedAsync() {
lock (mutex) { lock (mutex) {
if (SessionToken == null || CurrentUser == null || CurrentUser.ObjectId != ObjectId) { if (SessionToken == null || CurrentUser == null || CurrentUser.ObjectId != ObjectId) {
return Task.FromResult(false); return false;
} }
} }
var command = new AVCommand { var command = new AVCommand {
Path = $"users/me?session_token={CurrentSessionToken}", Path = $"users/me?session_token={SessionToken}",
Method = HttpMethod.Get Method = HttpMethod.Get
}; };
return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command); await AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
return true;
} }
/// <summary> /// <summary>
/// Refresh this user's session token, and current session token will be invalid. /// 刷新用户的 Session Token刷新后 Session Token 将会改变
/// </summary> /// </summary>
public Task RefreshSessionTokenAsync(CancellationToken cancellationToken) { /// <returns></returns>
return UserController.RefreshSessionTokenAsync(ObjectId, SessionToken, cancellationToken).OnSuccess(t => { public async Task RefreshSessionTokenAsync() {
var serverState = t.Result; var serverState = await UserController.RefreshSessionTokenAsync(ObjectId);
HandleSave(serverState); HandleSave(serverState);
});
} }
/// <summary> /// <summary>
/// authenticated token. /// 获取 Session Token
/// </summary> /// </summary>
public string SessionToken { public string SessionToken {
get { get {
@ -84,53 +68,47 @@ namespace LeanCloud {
} }
} }
internal static string CurrentSessionToken {
get {
return CurrentUser?.SessionToken;
}
}
internal void SetSessionTokenAsync(string newSessionToken) {
SetSessionTokenAsync(newSessionToken, CancellationToken.None);
}
internal void SetSessionTokenAsync(string newSessionToken, CancellationToken cancellationToken) {
MutateState(mutableClone => {
mutableClone.ServerData["sessionToken"] = newSessionToken;
});
CurrentUser = this;
}
/// <summary> /// <summary>
/// Gets or sets the username. /// 用户名
/// </summary> /// </summary>
[AVFieldName("username")] [AVFieldName("username")]
public string Username { public string Username {
get { return GetProperty<string>(null, "Username"); } get {
set { SetProperty(value, "Username"); } return GetProperty<string>(null, "Username");
}
set {
SetProperty(value, "Username");
}
} }
/// <summary> /// <summary>
/// Sets the password. /// 密码
/// </summary> /// </summary>
[AVFieldName("password")] [AVFieldName("password")]
public string Password { public string Password {
private get { return GetProperty<string>(null, "Password"); } private get {
set { SetProperty(value, "Password"); } return GetProperty<string>(null, "Password");
}
set {
SetProperty(value, "Password");
}
} }
/// <summary> /// <summary>
/// Sets the email address. /// Email
/// </summary> /// </summary>
[AVFieldName("email")] [AVFieldName("email")]
public string Email { public string Email {
get { return GetProperty<string>(null, "Email"); } get {
set { SetProperty(value, "Email"); } return GetProperty<string>(null, "Email");
}
set {
SetProperty(value, "Email");
}
} }
/// <summary> /// <summary>
/// 用户手机号。 /// 手机号。
/// </summary> /// </summary>
[AVFieldName("mobilePhoneNumber")] [AVFieldName("mobilePhoneNumber")]
public string MobilePhoneNumber { public string MobilePhoneNumber {
@ -138,21 +116,21 @@ namespace LeanCloud {
return GetProperty<string>(null, "MobilePhoneNumber"); return GetProperty<string>(null, "MobilePhoneNumber");
} }
set { set {
SetProperty<string>(value, "MobilePhoneNumber"); SetProperty(value, "MobilePhoneNumber");
} }
} }
/// <summary> /// <summary>
/// 用户手机号是否已经验证 /// 手机号是否已经验证
/// </summary> /// </summary>
/// <value><c>true</c> if mobile phone verified; otherwise, <c>false</c>.</value> /// <value><c>true</c> if mobile phone verified; otherwise, <c>false</c>.</value>
[AVFieldName("mobilePhoneVerified")] [AVFieldName("mobilePhoneVerified")]
public bool MobilePhoneVerified { public bool MobilePhoneVerified {
get { get {
return GetProperty<bool>(false, "MobilePhoneVerified"); return GetProperty(false, "MobilePhoneVerified");
} }
set { set {
SetProperty<bool>(value, "MobilePhoneVerified"); SetProperty(value, "MobilePhoneVerified");
} }
} }
@ -161,11 +139,7 @@ namespace LeanCloud {
/// </summary> /// </summary>
public bool IsAnonymous { public bool IsAnonymous {
get { get {
bool rtn = false; return AuthData != null && AuthData.Keys.Contains("anonymous");
if (this.AuthData != null) {
rtn = this.AuthData.Keys.Contains("anonymous");
}
return rtn;
} }
} }
@ -285,68 +259,38 @@ namespace LeanCloud {
return GetFolloweeQuery().FindAsync(CancellationToken.None); return GetFolloweeQuery().FindAsync(CancellationToken.None);
} }
//public Task<AVStatus> SendStatusAsync()
//{
//}
#endregion #endregion
/// <summary> /// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you /// 使用用户名和密码登陆。登陆成功后,将用户设置为当前用户
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary> /// </summary>
/// <param name="username">The username to log in with.</param> /// <param name="username">用户名</param>
/// <param name="password">The password to log in with.</param> /// <param name="password">密码</param>
/// <returns>The newly logged-in user.</returns> /// <returns></returns>
public static Task<AVUser> LogInAsync(string username, string password) { public static async Task<AVUser> LogInAsync(string username, string password) {
return LogInAsync(username, password, CancellationToken.None); var ret = await UserController.LogInAsync(username, null, password);
}
public static async Task<AVUser> LogInAsync(string username, string password, CancellationToken cancellationToken) {
var ret = await UserController.LogInAsync(username, null, password, cancellationToken);
AVUser user = FromState<AVUser>(ret, "_User"); AVUser user = FromState<AVUser>(ret, "_User");
CurrentUser = user; CurrentUser = user;
return user; return user;
} }
/// <summary> /// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you /// 使用 Session Token 登录。
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary> /// </summary>
/// <param name="sessionToken">The session token to authorize with</param> /// <param name="sessionToken">Session Token</param>
/// <returns>The user if authorization was successful</returns> /// <returns></returns>
public static Task<AVUser> BecomeAsync(string sessionToken) { public static async Task<AVUser> BecomeAsync(string sessionToken) {
return BecomeAsync(sessionToken, CancellationToken.None); var ret = await UserController.GetUserAsync(sessionToken);
}
/// <summary>
/// Logs in a user with a username and password. On success, this saves the session to disk so you
/// can retrieve the currently logged in user using <see cref="CurrentUser"/>.
/// </summary>
/// <param name="sessionToken">The session token to authorize with</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The user if authorization was successful</returns>
public static async Task<AVUser> BecomeAsync(string sessionToken, CancellationToken cancellationToken) {
var ret = await UserController.GetUserAsync(sessionToken, cancellationToken);
AVUser user = FromState<AVUser>(ret, "_User"); AVUser user = FromState<AVUser>(ret, "_User");
CurrentUser = user; CurrentUser = user;
return user; return user;
} }
/// <summary> /// <summary>
/// Logs out the currently logged in user session. This will remove the session from disk, log out of /// 用户登出
/// linked services, and future calls to <see cref="CurrentUser"/> will return <c>null</c>.
/// </summary> /// </summary>
/// <remarks>
/// Typically, you should use <see cref="LogOutAsync()"/>, unless you are managing your own threading.
/// </remarks>
public static void LogOut() { public static void LogOut() {
CurrentUser = null; CurrentUser = null;
// TODO (hallucinogen): this will without a doubt fail in Unity. But what else can we do?
//LogOutAsync().Wait();
} }
private static void LogOutWithProviders() { private static void LogOutWithProviders() {
@ -355,13 +299,16 @@ namespace LeanCloud {
} }
} }
/// <summary>
/// 获取当前用户
/// </summary>
public static AVUser CurrentUser { public static AVUser CurrentUser {
get; get;
internal set; internal set;
} }
/// <summary> /// <summary>
/// Constructs a <see cref="AVQuery{AVUser}"/> for AVUsers. /// 创建一个 AVUser 查询对象
/// </summary> /// </summary>
public static AVQuery<AVUser> Query { public static AVQuery<AVUser> Query {
get { get {
@ -370,34 +317,23 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// Requests a password reset email to be sent to the specified email address associated with the /// 通过绑定的邮箱请求重置密码
/// user account. This email allows the user to securely reset their password on the LeanCloud site. /// 邮件可以在 LeanCloud 站点安全的重置密码
/// </summary> /// </summary>
/// <param name="email">The email address associated with the user that forgot their password.</param> /// <param name="email">绑定的邮箱地址</param>
/// <returns></returns>
public static Task RequestPasswordResetAsync(string email) { public static Task RequestPasswordResetAsync(string email) {
return RequestPasswordResetAsync(email, CancellationToken.None); return UserController.RequestPasswordResetAsync(email);
} }
/// <summary> /// <summary>
/// Requests a password reset email to be sent to the specified email address associated with the /// 更新用户的密码,需要用户的旧密码
/// user account. This email allows the user to securely reset their password on the LeanCloud site.
/// </summary> /// </summary>
/// <param name="email">The email address associated with the user that forgot their password.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public static Task RequestPasswordResetAsync(string email,
CancellationToken cancellationToken) {
return UserController.RequestPasswordResetAsync(email, cancellationToken);
}
/// <summary>
/// Updates current user's password. Need the user's old password,
/// </summary>
/// <returns>The password.</returns>
/// <param name="oldPassword">Old password.</param> /// <param name="oldPassword">Old password.</param>
/// <param name="newPassword">New password.</param> /// <param name="newPassword">New password.</param>
/// <param name="cancellationToken">Cancellation token.</param> public async Task UpdatePasswordAsync(string oldPassword, string newPassword) {
public Task UpdatePassword(string oldPassword, string newPassword, CancellationToken cancellationToken) { IObjectState state = await UserController.UpdatePasswordAsync(ObjectId, oldPassword, newPassword);
return UserController.UpdatePasswordAsync(ObjectId, SessionToken, oldPassword, newPassword, cancellationToken); HandleFetchResult(state);
} }
/// <summary> /// <summary>
@ -545,42 +481,22 @@ namespace LeanCloud {
#region 手机号登录 #region 手机号登录
internal static async Task<AVUser> LogInWithParametersAsync(Dictionary<string, object> strs, CancellationToken cancellationToken) { internal static async Task<AVUser> LogInWithParametersAsync(Dictionary<string, object> strs) {
var ret = await UserController.LogInWithParametersAsync("login", strs, cancellationToken); var ret = await UserController.LogInWithParametersAsync("login", strs);
var user = CreateWithoutData<AVUser>(null); var user = CreateWithoutData<AVUser>(null);
user.HandleFetchResult(ret); user.HandleFetchResult(ret);
CurrentUser = user; CurrentUser = user;
return CurrentUser; return CurrentUser;
} }
/// <summary>
/// 以手机号和密码实现登陆。
/// </summary>
/// <param name="mobilePhoneNumber">手机号</param>
/// <param name="password">密码</param>
/// <returns></returns>
public static Task<AVUser> LogInByMobilePhoneNumberAsync(string mobilePhoneNumber, string password) {
return AVUser.LogInByMobilePhoneNumberAsync(mobilePhoneNumber, password, CancellationToken.None);
}
/// <summary>
/// 以手机号和验证码匹配登陆
/// </summary>
/// <param name="mobilePhoneNumber">手机号</param>
/// <param name="smsCode">短信验证码</param>
/// <returns></returns>
public static Task<AVUser> LogInBySmsCodeAsync(string mobilePhoneNumber, string smsCode) {
return AVUser.LogInBySmsCodeAsync(mobilePhoneNumber, smsCode, CancellationToken.None);
}
/// <summary> /// <summary>
/// 用邮箱作和密码匹配登录 /// 用邮箱作和密码匹配登录
/// </summary> /// </summary>
/// <param name="email">邮箱</param> /// <param name="email">邮箱</param>
/// <param name="password">密码</param> /// <param name="password">密码</param>
/// <returns></returns> /// <returns></returns>
public static async Task<AVUser> LogInByEmailAsync(string email, string password, CancellationToken cancellationToken = default(CancellationToken)) { public static async Task<AVUser> LogInByEmailAsync(string email, string password) {
var ret = await UserController.LogInAsync(null, email, password, cancellationToken); var ret = await UserController.LogInAsync(null, email, password);
AVUser user = FromState<AVUser>(ret, "_User"); AVUser user = FromState<AVUser>(ret, "_User");
CurrentUser = user; CurrentUser = user;
return CurrentUser; return CurrentUser;
@ -588,35 +504,31 @@ namespace LeanCloud {
/// <summary> /// <summary>
/// 手机号和密码匹配登陆 /// 手机号和密码匹配登陆
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">手机号</param> /// <param name="mobilePhoneNumber">手机号</param>
/// <param name="password">密码</param> /// <param name="password">密码</param>
/// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public static Task<AVUser> LogInByMobilePhoneNumberAsync(string mobilePhoneNumber, string password, CancellationToken cancellationToken) { public static Task<AVUser> LogInByMobilePhoneNumberAsync(string mobilePhoneNumber, string password) {
Dictionary<string, object> strs = new Dictionary<string, object>() Dictionary<string, object> strs = new Dictionary<string, object> {
{
{ "mobilePhoneNumber", mobilePhoneNumber }, { "mobilePhoneNumber", mobilePhoneNumber },
{ "password", password } { "password", password }
}; };
return AVUser.LogInWithParametersAsync(strs, cancellationToken); return LogInWithParametersAsync(strs);
} }
/// <summary> /// <summary>
/// 手机号和验证码登陆 /// 手机号和验证码登陆
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">手机号</param> /// <param name="mobilePhoneNumber">手机号</param>
/// <param name="smsCode">短信验证码</param> /// <param name="smsCode">短信验证码</param>
/// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public static Task<AVUser> LogInBySmsCodeAsync(string mobilePhoneNumber, string smsCode, CancellationToken cancellationToken = default(CancellationToken)) { public static Task<AVUser> LogInBySmsCodeAsync(string mobilePhoneNumber, string smsCode) {
Dictionary<string, object> strs = new Dictionary<string, object>() Dictionary<string, object> strs = new Dictionary<string, object> {
{
{ "mobilePhoneNumber", mobilePhoneNumber }, { "mobilePhoneNumber", mobilePhoneNumber },
{ "smsCode", smsCode } { "smsCode", smsCode }
}; };
return AVUser.LogInWithParametersAsync(strs, cancellationToken); return LogInWithParametersAsync(strs);
} }
/// <summary> /// <summary>
@ -672,34 +584,27 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// 手机号一键登录 /// 手机号注册和登录
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">手机号</param> /// <param name="mobilePhoneNumber">手机号</param>
/// <param name="smsCode">短信验证码</param> /// <param name="smsCode">短信验证码</param>
/// <returns></returns> /// <returns></returns>
public static async Task<AVUser> SignUpOrLogInByMobilePhoneAsync(string mobilePhoneNumber, string smsCode, CancellationToken cancellationToken) { public static async Task<AVUser> SignUpOrLogInByMobilePhoneAsync(string mobilePhoneNumber, string smsCode) {
Dictionary<string, object> strs = new Dictionary<string, object> { Dictionary<string, object> strs = new Dictionary<string, object> {
{ "mobilePhoneNumber", mobilePhoneNumber }, { "mobilePhoneNumber", mobilePhoneNumber },
{ "smsCode", smsCode } { "smsCode", smsCode }
}; };
var ret = await UserController.LogInWithParametersAsync("usersByMobilePhone", strs, cancellationToken); var ret = await UserController.LogInWithParametersAsync("usersByMobilePhone", strs);
var user = CreateWithoutData<AVUser>(null); var user = CreateWithoutData<AVUser>(null);
user.HandleFetchResult(ret); user.HandleFetchResult(ret);
CurrentUser = user; CurrentUser = user;
return CurrentUser; return CurrentUser;
} }
/// <summary> #endregion
/// 手机号一键登录
/// </summary> #region 手机短信
/// <returns>signup or login by mobile phone async.</returns>
/// <param name="mobilePhoneNumber">手机号</param>
/// <param name="smsCode">短信验证码</param>
public static Task<AVUser> SignUpOrLogInByMobilePhoneAsync(string mobilePhoneNumber, string smsCode) {
return AVUser.SignUpOrLogInByMobilePhoneAsync(mobilePhoneNumber, smsCode, CancellationToken.None);
}
#region mobile sms shortcode sign up & log in.
/// <summary> /// <summary>
/// Send sign up sms code async. /// Send sign up sms code async.
/// </summary> /// </summary>
@ -716,7 +621,7 @@ namespace LeanCloud {
/// <param name="mobilePhoneNumber">Mobile phone number.</param> /// <param name="mobilePhoneNumber">Mobile phone number.</param>
/// <param name="smsCode">Sms code.</param> /// <param name="smsCode">Sms code.</param>
public static Task<AVUser> SignUpByMobilePhoneAsync(string mobilePhoneNumber, string smsCode) { public static Task<AVUser> SignUpByMobilePhoneAsync(string mobilePhoneNumber, string smsCode) {
return AVUser.SignUpOrLogInByMobilePhoneAsync(mobilePhoneNumber, smsCode); return SignUpOrLogInByMobilePhoneAsync(mobilePhoneNumber, smsCode);
} }
/// <summary> /// <summary>
@ -725,7 +630,7 @@ namespace LeanCloud {
/// <returns>The log in sms code async.</returns> /// <returns>The log in sms code async.</returns>
/// <param name="mobilePhoneNumber">Mobile phone number.</param> /// <param name="mobilePhoneNumber">Mobile phone number.</param>
public static Task SendLogInSmsCodeAsync(string mobilePhoneNumber) { public static Task SendLogInSmsCodeAsync(string mobilePhoneNumber) {
return AVUser.RequestLogInSmsCodeAsync(mobilePhoneNumber); return RequestLogInSmsCodeAsync(mobilePhoneNumber);
} }
/// <summary> /// <summary>
@ -735,14 +640,15 @@ namespace LeanCloud {
/// <param name="mobilePhoneNumber">Mobile phone number.</param> /// <param name="mobilePhoneNumber">Mobile phone number.</param>
/// <param name="smsCode">Sms code.</param> /// <param name="smsCode">Sms code.</param>
public static Task<AVUser> LogInByMobilePhoneAsync(string mobilePhoneNumber, string smsCode) { public static Task<AVUser> LogInByMobilePhoneAsync(string mobilePhoneNumber, string smsCode) {
return AVUser.LogInBySmsCodeAsync(mobilePhoneNumber, smsCode); return LogInBySmsCodeAsync(mobilePhoneNumber, smsCode);
} }
#endregion
#endregion #endregion
#region 重置密码 #region 重置密码
/// <summary> /// <summary>
/// 请求重置密码,需要传入注册时使用的手机号。 /// 请求重置密码,需要传入注册时使用的手机号。
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">注册时使用的手机号</param> /// <param name="mobilePhoneNumber">注册时使用的手机号</param>
/// <returns></returns> /// <returns></returns>
@ -751,7 +657,7 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// 请求重置密码,需要传入注册时使用的手机号。 /// 请求重置密码,需要传入注册时使用的手机号。
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">注册时使用的手机号</param> /// <param name="mobilePhoneNumber">注册时使用的手机号</param>
/// <param name="cancellationToken">cancellationToken</param> /// <param name="cancellationToken">cancellationToken</param>
@ -761,7 +667,7 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// 请求重置密码,需要传入注册时使用的手机号。 /// 请求重置密码,需要传入注册时使用的手机号。
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">注册时使用的手机号</param> /// <param name="mobilePhoneNumber">注册时使用的手机号</param>
/// <param name="validateToken">Validate token.</param> /// <param name="validateToken">Validate token.</param>
@ -771,7 +677,7 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// 请求重置密码,需要传入注册时使用的手机号。 /// 请求重置密码,需要传入注册时使用的手机号。
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">注册时使用的手机号</param> /// <param name="mobilePhoneNumber">注册时使用的手机号</param>
/// <param name="validateToken">Validate token.</param> /// <param name="validateToken">Validate token.</param>
@ -822,42 +728,12 @@ namespace LeanCloud {
} }
/// <summary> /// <summary>
/// 发送认证码到需要认证的手机上 /// 发送验证码到用户绑定的手机上
/// </summary> /// </summary>
/// <param name="mobilePhoneNumber">手机号</param> /// <param name="mobilePhoneNumber">手机号</param>
/// <param name="validateToken">验证码</param>
/// <returns></returns> /// <returns></returns>
public static Task RequestMobilePhoneVerifyAsync(string mobilePhoneNumber) { public static Task RequestMobilePhoneVerifyAsync(string mobilePhoneNumber, string validateToken = null) {
return RequestMobilePhoneVerifyAsync(mobilePhoneNumber, null, CancellationToken.None);
}
/// <summary>
/// 发送认证码到需要认证的手机上
/// </summary>
/// <param name="mobilePhoneNumber">手机号</param>
/// <param name="validateToken">Validate token.</param>
/// <returns></returns>
public static Task RequestMobilePhoneVerifyAsync(string mobilePhoneNumber, string validateToken) {
return RequestMobilePhoneVerifyAsync(mobilePhoneNumber, validateToken, CancellationToken.None);
}
/// <summary>
/// 发送认证码到需要认证的手机上
/// </summary>
/// <param name="mobilePhoneNumber">手机号</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns></returns>
public static Task RequestMobilePhoneVerifyAsync(string mobilePhoneNumber, CancellationToken cancellationToken) {
return RequestMobilePhoneVerifyAsync(mobilePhoneNumber, null, cancellationToken);
}
/// <summary>
/// 发送认证码到需要认证的手机上
/// </summary>
/// <param name="mobilePhoneNumber">手机号</param>
/// <param name="validateToken">Validate token.</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns></returns>
public static Task RequestMobilePhoneVerifyAsync(string mobilePhoneNumber, string validateToken, CancellationToken cancellationToken) {
Dictionary<string, object> strs = new Dictionary<string, object> { Dictionary<string, object> strs = new Dictionary<string, object> {
{ "mobilePhoneNumber", mobilePhoneNumber } { "mobilePhoneNumber", mobilePhoneNumber }
}; };
@ -872,31 +748,6 @@ namespace LeanCloud {
return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command); return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
} }
/// <summary>
/// 验证手机验证码是否为有效值
/// </summary>
/// <param name="code">手机收到的验证码</param>
/// <param name="mobilePhoneNumber">手机号</param>
/// <returns></returns>
public static Task VerifyMobilePhoneAsync(string code, string mobilePhoneNumber) {
return VerifyMobilePhoneAsync(code, mobilePhoneNumber, CancellationToken.None);
}
/// <summary>
/// 验证手机验证码是否为有效值
/// </summary>
/// <param name="code">手机收到的验证码</param>
/// <param name="mobilePhoneNumber">手机号,可选</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task VerifyMobilePhoneAsync(string code, string mobilePhoneNumber, CancellationToken cancellationToken) {
var command = new AVCommand {
Path = $"verifyMobilePhone/{code.Trim()}?mobilePhoneNumber={mobilePhoneNumber.Trim()}",
Method = HttpMethod.Post
};
return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
}
/// <summary> /// <summary>
/// 验证手机验证码是否为有效值 /// 验证手机验证码是否为有效值
/// </summary> /// </summary>
@ -910,19 +761,10 @@ namespace LeanCloud {
return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command); return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
} }
/// <summary>
/// 验证手机验证码是否为有效值
/// </summary>
/// <param name="code">手机收到的验证码</param>
/// <param name="cancellationToken">cancellationToken</param>
/// <returns></returns>
public static Task<bool> VerifyMobilePhoneAsync(string code, CancellationToken cancellationToken) {
return AVUser.VerifyMobilePhoneAsync(code, CancellationToken.None);
}
#endregion #endregion
#region 邮箱验证 #region 邮箱验证
/// <summary> /// <summary>
/// 申请发送验证邮箱的邮件,一周之内有效 /// 申请发送验证邮箱的邮件,一周之内有效
/// 如果该邮箱已经验证通过,会直接返回 True并不会真正发送邮件 /// 如果该邮箱已经验证通过,会直接返回 True并不会真正发送邮件
@ -931,8 +773,7 @@ namespace LeanCloud {
/// <param name="email">邮箱地址</param> /// <param name="email">邮箱地址</param>
/// <returns></returns> /// <returns></returns>
public static Task RequestEmailVerifyAsync(string email) { public static Task RequestEmailVerifyAsync(string email) {
Dictionary<string, object> strs = new Dictionary<string, object>() Dictionary<string, object> strs = new Dictionary<string, object> {
{
{ "email", email } { "email", email }
}; };
var command = new AVCommand { var command = new AVCommand {
@ -942,6 +783,7 @@ namespace LeanCloud {
}; };
return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command); return AVPlugins.Instance.CommandRunner.RunCommandAsync<IDictionary<string, object>>(command);
} }
#endregion #endregion
#region in no-local-storage enviroment #region in no-local-storage enviroment
@ -988,9 +830,11 @@ namespace LeanCloud {
return t; return t;
}).Unwrap(); }).Unwrap();
} }
#endregion #endregion
#region AVUser Extension #region AVUser Extension
public IDictionary<string, IDictionary<string, object>> GetAuthData() { public IDictionary<string, IDictionary<string, object>> GetAuthData() {
return AuthData; return AuthData;
} }
@ -1009,7 +853,7 @@ namespace LeanCloud {
if (options == null) { if (options == null) {
options = new AVUserAuthDataLogInOption(); options = new AVUserAuthDataLogInOption();
} }
return AVUser.LogInWithAsync(platform, data, options.FailOnNotExist, cancellationToken); return LogInWithAsync(platform, data, options.FailOnNotExist, cancellationToken);
} }
public static Task<AVUser> LogInWithAuthDataAndUnionIdAsync( public static Task<AVUser> LogInWithAuthDataAndUnionIdAsync(
@ -1022,7 +866,7 @@ namespace LeanCloud {
options = new AVUserAuthDataLogInOption(); options = new AVUserAuthDataLogInOption();
} }
MergeAuthData(authData, unionId, options); MergeAuthData(authData, unionId, options);
return AVUser.LogInWithAsync(platform, authData, options.FailOnNotExist, cancellationToken); return LogInWithAsync(platform, authData, options.FailOnNotExist, cancellationToken);
} }
public static Task<AVUser> LogInAnonymouslyAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { public static Task<AVUser> LogInAnonymouslyAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken)) {
@ -1035,13 +879,12 @@ namespace LeanCloud {
[Obsolete("please use LogInWithAuthDataAsync instead.")] [Obsolete("please use LogInWithAuthDataAsync instead.")]
public static Task<AVUser> LogInWithAsync(string authType, IDictionary<string, object> data, CancellationToken cancellationToken) { public static Task<AVUser> LogInWithAsync(string authType, IDictionary<string, object> data, CancellationToken cancellationToken) {
return AVUser.LogInWithAsync(authType, data, false, cancellationToken); return LogInWithAsync(authType, data, false, cancellationToken);
} }
/// <summary> /// <summary>
/// link a 3rd auth account to the user. /// link a 3rd auth account to the user.
/// </summary> /// </summary>
/// <param name="user">AVUser instance</param>
/// <param name="data">OAuth data, like {"accessToken":"xxxxxx"}</param> /// <param name="data">OAuth data, like {"accessToken":"xxxxxx"}</param>
/// <param name="platform">auth platform,maybe "facebook"/"twiiter"/"weibo"/"weixin" .etc</param> /// <param name="platform">auth platform,maybe "facebook"/"twiiter"/"weibo"/"weixin" .etc</param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
@ -1066,7 +909,6 @@ namespace LeanCloud {
/// <summary> /// <summary>
/// unlink a 3rd auth account from the user. /// unlink a 3rd auth account from the user.
/// </summary> /// </summary>
/// <param name="user">AVUser instance</param>
/// <param name="platform">auth platform,maybe "facebook"/"twiiter"/"weibo"/"weixin" .etc</param> /// <param name="platform">auth platform,maybe "facebook"/"twiiter"/"weibo"/"weixin" .etc</param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
@ -1080,6 +922,7 @@ namespace LeanCloud {
authData["main_account"] = options.AsMainAccount; authData["main_account"] = options.AsMainAccount;
authData["unionid"] = unionId; authData["unionid"] = unionId;
} }
#endregion #endregion
} }
} }