/// <summary> /// Logs into ParticleCloud with the given username and password /// </summary> /// <param name="username">The Particle account username</param> /// <param name="password">The Particle account password</param> /// <param name="expiresIn">How many seconds the token will be valid for. 0 means forever. Short lived tokens are better for security.</param> /// <returns>Result if Result.Success == true the user is logged in if its false the user is not logged in and ErrorMessage will contain the error from the server</returns> public async Task<Result> LoginWithUserAsync(String username, String password, int expiresIn = 3600) { if (String.IsNullOrWhiteSpace(username)) { throw new ArgumentNullException(nameof(username)); } if (String.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException(nameof(password)); } client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("particle:particle"))); var data = new Dictionary<String, String>(); data["grant_type"] = "password"; data["username"] = username; data["password"] = password; data["expires_in"] = expiresIn.ToString(); // BaseAddress did not seam to work on Linux so changed to use UriBuilder UriBuilder b = new UriBuilder(baseUri); b.Path = "/oauth/token"; try { var postResults = await client.PostAsync(b.Uri, new FormUrlEncodedContent(data)); if (postResults.StatusCode == System.Net.HttpStatusCode.OK) { var results = await postResults.Content.ReadAsStringAsync(); var ret = await Task.Run(() => JsonConvert.DeserializeObject<AuthenticationResults>(results)); if (ret != null) { if (!String.IsNullOrWhiteSpace(ret.AccessToken)) { authResults = ret; authResults.Username = username; authResults.Password = password; return new Result { Success = true }; } } } else if (postResults.StatusCode == System.Net.HttpStatusCode.BadRequest) { var results = await postResults.Content.ReadAsStringAsync(); var ret = await Task.Run(() => JsonConvert.DeserializeObject<Result>(results)); if (ret != null) { ret.Success = false; return ret; } } return new Result { Success = false, Error = postResults.StatusCode.ToString() }; } catch (HttpRequestException re) { return new Result { Success = false, Error = re.Message, Exception = re }; } }
/// <summary> /// Logs the user out locally /// </summary> public void Logout() { authResults = null; }
/// <summary> /// Logs the user out locally /// </summary> public void Logout() { authResults = null; FirePropertyChanged(nameof(IsAuthenticated)); }