public override void OnClearToken(AuthToken token) { HttpCookie cookie = HttpContext.Current.Request.Cookies["token"]; if (cookie != null) { cookie.Expires = DateTime.Now.AddYears(-1); HttpContext.Current.Response.Cookies.Add(cookie); } }
public override void OnAuthenticationComplete(AuthToken token) { string xml = XmlToObject<AuthToken>.Serialize(token); /// create a cookie out of it. var authCookie = new HttpCookie("token", HttpUtility.UrlEncode(xml)); /// set exipration. authCookie.Expires = DateTime.Now.AddDays(30); /// put it to response. HttpContext.Current.Response.Cookies.Add(authCookie); }
public void TearUp() { _authTokenConfig = new GenericConfiguration<AuthToken>(); _clientLogin = new GenericConfiguration<ClientLogin>(); _authTokenConfig.Setup(); //_clientLogin.Setup(); _authTokenList = TokenHelper.GetTokenModelList(); _clientLoginList = TokenHelper.GetClientLoginList(); _tokenModel = TokenHelper.GetModel(); _authToken = TokenHelper.GetAuthTokenModel(); }
private const int tokenValidity = 30;//30 min public string GetUserToken(string username) { if (string.IsNullOrEmpty(username)) throw new ArgumentNullException("username"); var token = new AuthToken(username); if (!tokenInfos.ContainsKey(token.Token)) { tokenInfos.Add(token.Token, token); return token.Token; } return string.Empty; }
public void saveToken(AuthToken token) { clearTokens (); var newAccount = new Account (); newAccount.Username = token.accessToken; if (token.expiresIn != null) { newAccount.Properties.Add ("exires_in", token.expiresIn); } if (token.tokenType != null) { newAccount.Properties.Add ("token_type", token.tokenType); } if (token.scope != null) { newAccount.Properties.Add ("scope", token.scope); } if (token.refreshToken != null) { newAccount.Properties.Add ("refresh_token", token.refreshToken); } store.Save (newAccount, context); }
public async Task SetToken(AuthToken token) { ServiceLocator.Resolve<IClient>().SetToken(token); var user = await ServiceLocator.Resolve<UserAPI>().GetSelf(); BoardListVM = new BoardListViewModel(this, GetBoardList); User = user; IsLogin = true; await StorageHelper.SaveLocal(token); await StorageHelper.SaveLocal(user); }
private void NotAuthorizedToken(object sender, NotAuthorizedTokenEventArgs e) { IAuthServices client = sender as IAuthServices; if (null != client) { token = client.GetToken(); AuthorizationForm authorization = new AuthorizationForm(token.Url); if (authorization.ShowDialog() == DialogResult.OK) { e.NewToken = token; e.Resolved = true; } } }
public async Task<AuthToken> RefreshToken(AuthToken token) { try { var resphonse = await Post( Client.API_TOKEN, new KeyValuePair<string, string>("grant_type", "refresh_token"), new KeyValuePair<string, string>("refresh_token", token.refresh_token) ); return AuthToken.Parse(resphonse); } catch { } return null; }
public static bool Create(AuthToken authToken, string queueName, QueueDescription queueDescription) { try { if (!Exists(authToken, queueName)) { Management.Queues q = new Management.Queues(authToken); q.Create(queueName, queueDescription); } return true; } catch (Exception ex) { throw ex; } }
public AuthToken getToken() { var account = store.FindAccountsForService (context).FirstOrDefault (); if (account == null) { return null; } else { var token = new AuthToken(); token.accessToken = account.Username; if (account.Properties.ContainsKey("expires_in")) { token.expiresIn = account.Properties ["expires_in"]; } if (account.Properties.ContainsKey("token_type")) { token.tokenType = account.Properties ["token_type"]; } if (account.Properties.ContainsKey("scope")) { token.scope = account.Properties ["scope"]; } if (account.Properties.ContainsKey("refresh_token")) { token.refreshToken = account.Properties ["refresh_token"]; } return token; } }
public Result <ScoreCustomerResponseISmart[]> Call(AuthToken authToken, List <(string IdNo, string FirstName, string Surname)> customers)
internal static void SetAuthToken(AuthToken authToken) { SessionAuthToken = authToken; }
protected static bool Supports(Version minVersion, AuthToken authToken) { return(authToken.ApiVersion >= minVersion); }
public AuthToken login(string AuthcateName, string AuthcatePassword) { var token = new AuthToken(AuthcateName); token.authenticated = false; return token; }
public async Task <TaskResult> Delete(ulong id, ulong user_id, string token) { AuthToken authToken = await Context.AuthTokens.FindAsync(token); // Return the same if the token is for the wrong user to prevent someone // from knowing if they cracked another user's token. This is basically // impossible to happen by chance but better safe than sorry in the case that // the literal impossible odds occur, more likely someone gets a stolen token // but is not aware of the owner but I'll shut up now - Spike if (authToken == null || authToken.User_Id != user_id) { return(new TaskResult(false, "Failed to authorize user.")); } PlanetCategory category = await Context.PlanetCategories.FindAsync(id); ServerPlanet planet = await ServerPlanet.FindAsync(category.Planet_Id); if (!(await planet.AuthorizedAsync(authToken, PlanetPermissions.ManageCategories))) { return(new TaskResult(false, "You are not authorized to do this.")); } List <PlanetCategory> cate = await Task.Run(() => Context.PlanetCategories.Where(x => x.Planet_Id == category.Planet_Id).ToList()); if (cate.Count == 1) { return(new TaskResult(false, "You can not delete your last category!")); } List <PlanetCategory> categories = await Task.Run(() => Context.PlanetCategories.Where(x => x.Parent_Id == id).ToList()); List <PlanetChatChannel> channels = await Task.Run(() => Context.PlanetChatChannels.Where(x => x.Parent_Id == id).ToList()); //Check if any channels in this category are the main channel foreach (PlanetChatChannel channel in channels) { if (channel.Id == planet.Main_Channel_Id) { return(new TaskResult(false, "You can not delete your main channel!")); } } //If not, then delete the channels foreach (PlanetChatChannel channel in channels) { Context.PlanetChatChannels.Remove(channel); } foreach (PlanetCategory Category in categories) { Category.Parent_Id = null; } ulong parentId = category.Planet_Id; Context.PlanetCategories.Remove(category); await Context.SaveChangesAsync(); await PlanetHub.Current.Clients.Group($"p-{parentId}").SendAsync("RefreshChannelList", ""); return(new TaskResult(true, "Successfully deleted.")); }
/// <summary> /// Initializes a new instance of the <see cref="TradierOptionExpirationCommand"/> class. /// </summary> /// <param name="model">The model.</param> internal TradierOptionExpirationCommand(AuthToken model) : base(model?.BaseUrl, model?.AccessKey) { }
public string Authenticate(string Username, string Password) { JavaScriptSerializer js = new JavaScriptSerializer(); JsonSerializerSettings j = new JsonSerializerSettings(); j.TypeNameHandling = TypeNameHandling.Objects; j.Formatting = Newtonsoft.Json.Formatting.Indented; string result = "ERR - Unknown"; string responseString = null; Response response = new Response(); UnitOfWork unitOfWork = new UnitOfWork(_sessionHelper.GetSessionFactory("APL")); Repository<Guid, User> userRepo = new Repository<Guid, User>(unitOfWork.Session); Repository<Guid, UserToken> userTokenRepo = new Repository<Guid, UserToken>(unitOfWork.Session); user = userRepo.FilterBy(x => x.Username == Username).FirstOrDefault(); if (user != null && user.Id != Guid.Empty) { if (Password == user.Password) { AuthToken token = new AuthToken(); if (!string.IsNullOrEmpty(user.AuthToken)) { if (CheckToken(user.AuthToken) == null) { user.AuthToken = null; } } if (string.IsNullOrEmpty(user.AuthToken)) { result = GenerateAuthToken(); APLBackendDB.UserToken userToken = new UserToken(); userToken.CreateDate = DateTime.Now; userToken.ExpiryDate = DateTime.Now.AddHours(4); userToken.LastUsedDate = DateTime.Now; userToken.Token = result; userToken.UserId = user.Id; userTokenRepo.Add(userToken); user.AuthToken = result; userRepo.Update(user); token.Token = result; } else { token.Token = user.AuthToken; } response.ResponseCode = "OK"; response.ResponseData = token; } else { response.ResponseCode = "ERR"; response.ResponseData = "Authentication failed."; } } else { response.ResponseCode = "ERR"; response.ResponseData = "User not found."; } js = new JavaScriptSerializer(); responseString = JsonConvert.SerializeObject(response, j); unitOfWork.Commit(); return responseString; }
public static bool Exists(AuthToken authToken, string topicName) { IList<string> topics = List(authToken); if (topics != null) { if (topics.Contains(topicName)) { return true; } } return false; }
public static QueueDefinition Definition(AuthToken authToken, string queueName) { try { Management.Queues q = new Management.Queues(authToken); return q.GetDefinition(queueName); } catch (Exception ex) { throw ex; //return null; } }
private void ChceckAndSet(SettingElement element) { if (publicProperties.ContainsKey(element.Name)) { isPreventSave = true; object value = element.GetValue(); if (typeof(TimeSpan) == publicProperties[element.Name].PropertyType) { value = new TimeSpan { Value = System.TimeSpan.Parse(value.ToString()) }; } else if (typeof(bool) == publicProperties[element.Name].PropertyType) { value = bool.Parse(value.ToString()); } else if (typeof(AuthToken) == publicProperties[element.Name].PropertyType) { value = new AuthToken { Token = value.ToString() }; } publicProperties[element.Name].SetValue(this, value, null); isPreventSave = false; } }
protected void UnityIosRequestAuthTokenCallback(string message) { LitJson.JsonReader reader = new LitJson.JsonReader(message); Dictionary<string, string> dict = new Dictionary<string, string>(); reader.Read(); JsonReadFlatObjectIntoDictionary(reader, dict); ErrorCode status = (ErrorCode)Enum.Parse(typeof(ErrorCode), dict["Status"]); AuthToken token = null; if (Error.Succeeded(status)) { token = new AuthToken(); token.Data = dict["Token"]; } RequestAuthTokenDoneCallback(status, token); }
protected override void SolveInstance(IGH_DataAccess DA) { //declare input variables bool useFilter = false; string nameFilter = ""; AuthToken authToken = new AuthToken(); //get data from user inputs if (DA.GetData<string>("Filter", ref nameFilter)) useFilter = true; if(!DA.GetData<AuthToken>("Token", ref authToken)) { return; } if (!authToken.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The provided authentication token appears to be invalid. Try re-running the Google Authenticator component."); return; } //declare output variables List<string> spreadsheetList = new List<string>(); OAuth2Parameters parameters = GDriveUtil.GetParameters(authToken); SpreadsheetsService service = GDriveUtil.GetSpreadsheetsService(parameters); SpreadsheetQuery query = new SpreadsheetQuery(); // Make a request to the API and get all spreadsheets. SpreadsheetFeed feed = service.Query(query); // Iterate through all of the spreadsheets returned foreach(var entry in feed.Entries){ string name = entry.Title.Text; bool addSpreadsheet = (useFilter) ? LikeOperator.LikeString(name, nameFilter, CompareMethod.Binary) : true; //test for matching spreadsheet name if filter has been specified if (addSpreadsheet) spreadsheetList.Add(name); } DA.SetDataList("Spreadsheets", spreadsheetList); //pass the spreadsheet list to the output parameter. }
/// <summary> /// Returns the planet membership of a user /// </summary> /// <param name="token"></param> /// <returns></returns> public async Task <TaskResult <List <Planet> > > GetPlanetMembership(ulong id, string token) { if (token == null) { return(new TaskResult <List <Planet> >(false, "Please supply an authentication token", null)); } AuthToken authToken = await Context.AuthTokens.FindAsync(token); if (authToken.User_Id != id) { return(new TaskResult <List <Planet> >(false, $"Could not authenticate for user {id}", null)); } if (!Permission.HasPermission(authToken.Scope, UserPermissions.Membership)) { return(new TaskResult <List <Planet> >(false, $"The given token does not have membership scope", null)); } List <Planet> membership = new List <Planet>(); // Remove this after pre-pre-alpha if (!(await Context.PlanetMembers.AnyAsync(x => x.Planet_Id == 7 && x.User_Id == id))) { PlanetMember newMember = new PlanetMember() { Planet_Id = 7, User_Id = id }; await Context.PlanetMembers.AddAsync(newMember); await Context.SaveChangesAsync(); } List <PlanetBan> bans = await Task.Run(() => Context.PlanetBans.Where(x => x.User_Id == id).ToList()); foreach (PlanetBan ban in bans) { if (ban.Permanent == false) { if (DateTime.UtcNow > ban.Time.AddMinutes((double)ban.Minutes)) { PlanetMember newMember = new PlanetMember() { Planet_Id = ban.Planet_Id, User_Id = ban.User_Id }; await Context.PlanetMembers.AddAsync(newMember); Context.PlanetBans.Remove(ban); await Context.SaveChangesAsync(); } } } foreach (PlanetMember member in Context.PlanetMembers.Where(x => x.User_Id == id)) { Planet planet = await Context.Planets.FindAsync(member.Planet_Id); if (await member.IsBanned(Context, planet.Id)) { Context.PlanetMembers.Remove(member); await Context.SaveChangesAsync(); } if (planet != null) { membership.Add(planet); } } return(new TaskResult <List <Planet> >(true, $"Retrieved {membership.Count} planets", membership)); }
protected override void SolveInstance(IGH_DataAccess DA) { //declare input variables AuthToken authToken = new AuthToken(); string sheetName = ""; string worksheet = ""; int offset = 0; List<string> data = new List<string>(); //get data from inputs if (!DA.GetData<AuthToken>("Token", ref authToken)) { return; //exit if no token } if (!authToken.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The provided authentication token appears to be invalid. Try re-running the Google Authenticator component."); return; //exit if invalid token } if (!DA.GetData<string>("Name", ref sheetName)) { return; //exit if no name given } DA.GetData<string>("Worksheet", ref worksheet); if (!DA.GetDataList("Data", data)) { return; //exit if no data to search for specified } DA.GetData("Offset", ref offset); //declare output variables List<string> cellList = new List<string>(data.Count); //set up authentication OAuth2Parameters parameters = GDriveUtil.GetParameters(authToken); SpreadsheetsService service = GDriveUtil.GetSpreadsheetsService(parameters); //find the spreadsheet SpreadsheetEntry spreadsheet = GDriveUtil.findSpreadsheetByName(sheetName,service); if (spreadsheet == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified Spreadsheet not found."); return; } //find the worksheet by name WorksheetEntry worksheetEntry = GDriveUtil.findWorksheetByName(worksheet, spreadsheet); if (worksheetEntry == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified worksheet not found."); return; } // Fetch the cell feed of the worksheet. CellQuery cellQuery = new CellQuery(worksheetEntry.CellFeedLink); CellFeed cellFeed = service.Query(cellQuery); //for each field the user is seeking: for(int i=0;i<data.Count;i++){ bool found = false; foreach (CellEntry cell in cellFeed.Entries) // for each cell { if(cell.Value.ToUpperInvariant().Equals(data[i].ToUpperInvariant())){ //case insensitive match of cell data CellEntry thisCell = cell; switch (offset) //user specified cell offset, by 0, +1 row, or +1 column { case 0: //no offset cellList.Add(cell.Title.Text); break; case 1: //+1 row offset cellList.Add(GDriveUtil.addressFromCells((int)cell.Column,(int)cell.Row+1)); break; case 2: //+1 column offset cellList.Add(GDriveUtil.addressFromCells((int)cell.Column+1, (int)cell.Row)); break; } found = true; break; //exit once first matching cell is found } } if (!found) { // alert user cell not found, but insert a null into the output list so that list output corresponds to inputs. AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, String.Format("{0} not found in sheet",data[i].ToString())); cellList.Add(null); } } DA.SetDataList("Cells", cellList); //pass cell addresses to output. }
public OAuthToken() { Token = new AuthToken(); }
protected void HandleAuthTokenRequestComplete(Twitch.ErrorCode result, AuthToken authToken) { if (Twitch.Error.Succeeded(result)) { PlayerPrefs.SetString(s_TwitchAuthTokenKey, authToken.Data); PlayerPrefs.SetString(s_TwitchUserNameKey, m_BroadcastController.UserName); DebugOverlay.Instance.AddViewportText("User authenticated", 2); } else { PlayerPrefs.DeleteKey(s_TwitchAuthTokenKey); PlayerPrefs.DeleteKey(s_TwitchUserNameKey); DebugOverlay.Instance.AddViewportText("Failed to authenticate", 2); } PlayerPrefs.Save(); }
/// <summary> /// Creates a server and if successful returns a task result with the created /// planet's id /// </summary> public async Task <TaskResult <ulong> > CreatePlanet(string name, string image_url, string token) { TaskResult nameValid = ValidateName(name); if (!nameValid.Success) { return(new TaskResult <ulong>(false, nameValid.Message, 0)); } AuthToken authToken = await Context.AuthTokens.FindAsync(token); if (authToken == null) { return(new TaskResult <ulong>(false, "Failed to authorize user.", 0)); } User user = await Context.Users.FindAsync(authToken.User_Id); if (await Context.Planets.CountAsync(x => x.Owner_Id == user.Id) > MAX_OWNED_PLANETS - 1) { return(new TaskResult <ulong>(false, "You have hit your maximum planets!", 0)); } // User is verified and given planet info is valid by this point // We don't actually need the user object which is cool // Use MSP for proxying image MSPResponse proxyResponse = await MSPManager.GetProxy(image_url); if (string.IsNullOrWhiteSpace(proxyResponse.Url) || !proxyResponse.Is_Media) { image_url = "https://valour.gg/image.png"; } else { image_url = proxyResponse.Url; } ulong planet_id = IdManager.Generate(); // Create general category PlanetCategory category = new PlanetCategory() { Id = IdManager.Generate(), Name = "General", Parent_Id = null, Planet_Id = planet_id, Position = 0 }; // Create general channel PlanetChatChannel channel = new PlanetChatChannel() { Id = IdManager.Generate(), Planet_Id = planet_id, Name = "General", Message_Count = 0, Description = "General chat channel", Parent_Id = category.Id }; // Create default role ServerPlanetRole defaultRole = new ServerPlanetRole() { Id = IdManager.Generate(), Planet_Id = planet_id, Position = uint.MaxValue, Color_Blue = 255, Color_Green = 255, Color_Red = 255, Name = "@everyone" }; ServerPlanet planet = new ServerPlanet() { Id = planet_id, Name = name, Member_Count = 1, Description = "A Valour server.", Image_Url = image_url, Public = true, Owner_Id = user.Id, Default_Role_Id = defaultRole.Id, Main_Channel_Id = channel.Id }; // Add planet to database await Context.Planets.AddAsync(planet); await Context.SaveChangesAsync(); // We must do this first to prevent foreign key errors // Add category to database await Context.PlanetCategories.AddAsync(category); // Add channel to database await Context.PlanetChatChannels.AddAsync(channel); // Add default role to database await Context.PlanetRoles.AddAsync(defaultRole); // Save changes await Context.SaveChangesAsync(); // Add owner to planet await planet.AddMemberAsync(user); // Return success return(new TaskResult <ulong>(true, "Successfully created planet.", planet.Id)); }
public bool RemoveItem(AuthToken token, Guid itemId) { return(false); }
public GoodsModel(Product currentProduct, AuthToken token) { CurrentProduct = currentProduct; ProductUri = Connector.GetPhotoUri(currentProduct.photo.link, token); }
void IStreamCallbacks.RequestAuthTokenCallback(ErrorCode result, AuthToken authToken) { }
public IngestionManager(AuthToken token, String baseAddress) { _httpHelper = new HttpHelper(baseAddress); _token = token; }
public void SetAuthToken(AuthToken currentAuthToken) { this.authToken = currentAuthToken; }
public override void Init() { base.Init(); Token = null; }
public UserController() { _userRepository = new UserRepository(); _authToken = new AuthToken(); }
internal static void RefreshAuthToken(AuthToken authToken) { // https://docs.uipath.com/orchestrator/v2019/reference#section-getting-authorization-code // TODO: handle token expiration if (!string.IsNullOrWhiteSpace(authToken.Token)) { return; } var api = new UiPathWebApi_19_4( new BasicAuthenticationCredentials()) { BaseUri = new Uri(authToken.AuthorizationUrl) }; JObject req = string.IsNullOrWhiteSpace(authToken.AuthorizationRefreshToken) ? new JObject( new JProperty("grant_type", "authorization_code"), new JProperty("redirect_uri", $"{authToken.AuthorizationUrl}/mobile"), new JProperty("client_id", authToken.ApplicationId)) : new JObject( new JProperty("grant_type", "refresh_token"), new JProperty("refresh_token", authToken.AuthorizationRefreshToken), new JProperty("client_id", authToken.ApplicationId)); api.MakeHttpRequest( HttpMethod.Post, "oauth/token", req, out var response, out var headers); var jr = JToken.Parse(response); var accessToken = jr.Value <string>("access_token"); var refreshToken = authToken.AuthorizationRefreshToken ?? jr.Value <string>("refresh_token"); var idToken = jr.Value <string>("id_token"); if (string.IsNullOrWhiteSpace(accessToken) || string.IsNullOrWhiteSpace(refreshToken) || string.IsNullOrWhiteSpace(idToken)) { throw new ApplicationException("The authorization response is missing the required tokens"); } api = new UiPathWebApi_19_4( new TokenCredentials(idToken)) { BaseUri = new Uri(authToken.AccountUrl) }; string accountLogicalName = authToken.AccountName; string tenantLogicalName = authToken.TenantName; authToken.Token = accessToken; authToken.AuthorizationRefreshToken = refreshToken; authToken.AuthorizationTokenId = idToken; authToken.URL = $"{authToken.AccountUrl}/{accountLogicalName}/{tenantLogicalName}/"; authToken.TenantName = tenantLogicalName; authToken.AccountName = accountLogicalName; }
public void Send(AuthToken authToken, Message message, string targetDevice) { Console.WriteLine("Sending a message as push notification."); }
public async Task <SessionToken> BeginSessionAsync( AuthToken token, string clientVersion, string accessKey, bool isLocal, float syncTime) { var game = gameData.Client; var user = gameData.GetUser(token.UserId); if (game == null) { return(null); } if (game.AccessKey != accessKey) { return(null); } var userId = token.UserId; var activeSession = gameData.GetUserSession(userId); // x => x.UserId == userId && x.Status == (int)SessionStatus.Active if (activeSession != null) { EndSession(activeSession); } var newGameSession = gameData.CreateSession(userId); gameData.Add(newGameSession); var sessionState = gameData.GetSessionState(newGameSession.Id); sessionState.SyncTime = syncTime; var isAdmin = user.IsAdmin.GetValueOrDefault(); var isModerator = user.IsModerator.GetValueOrDefault(); var subInfo = await twitchClient.GetSubscriberAsync(user.UserId); var subscriptionTier = 0; var expMultiplierLimit = 0; if (subInfo != null && int.TryParse(subInfo.Tier, out subscriptionTier)) { subscriptionTier /= 1000; expMultiplierLimit = subscriptionTier == 1 ? 10 : (subscriptionTier - 1) * 25; } if (isModerator) { subscriptionTier = 3; expMultiplierLimit = 50; } if (isAdmin) { subscriptionTier = 3; expMultiplierLimit = 5000; } if (isAdmin || isModerator || subInfo != null) { var permissionEvent = gameData.CreateSessionEvent( GameEventType.PermissionChange, newGameSession, new Permissions { IsAdministrator = user.IsAdmin ?? false, IsModerator = user.IsModerator ?? false, SubscriberTier = subscriptionTier, ExpMultiplierLimit = expMultiplierLimit, }); gameData.Add(permissionEvent); } var village = gameData.GetOrCreateVillageBySession(newGameSession); var villageHouses = gameData.GetOrCreateVillageHouses(village); var villageInfoEvent = gameData.CreateSessionEvent( GameEventType.VillageInfo, newGameSession, new VillageInfo { Name = village.Name, Level = village.Level, Experience = village.Experience, Houses = villageHouses.Select(x => new VillageHouseInfo { Owner = x.UserId != null ? gameData.GetUser(x.UserId.Value).UserId : null, Slot = x.Slot, Type = x.Type } ).ToList() } ); gameData.Add(villageInfoEvent); return(GenerateSessionToken(token, newGameSession)); }
public async void PopulateGuildsAndChannels() { // Create progress operation var operation = ProgressManager.CreateOperation(); try { // Sanitize token TokenValue = TokenValue !.Trim('"'); // Create token var token = new AuthToken( IsBotToken ? AuthTokenType.Bot : AuthTokenType.User, TokenValue); // Save token _settingsService.LastToken = token; // Prepare available guild list var availableGuilds = new List <GuildViewModel>(); // Get direct messages { // Get fake guild var guild = Guild.DirectMessages; // Get channels var channels = await _dataService.GetDirectMessageChannelsAsync(token); // Create channel view models var channelViewModels = new List <ChannelViewModel>(); foreach (var channel in channels) { // Get fake category var category = channel.Type == ChannelType.DirectTextChat ? "Private" : "Group"; // Create channel view model var channelViewModel = _viewModelFactory.CreateChannelViewModel(channel, category); // Add to list channelViewModels.Add(channelViewModel); } // Create guild view model var guildViewModel = _viewModelFactory.CreateGuildViewModel(guild, channelViewModels.OrderBy(c => c.Category) .ThenBy(c => c.Model.Name) .ToArray()); // Add to list availableGuilds.Add(guildViewModel); } // Get guilds var guilds = await _dataService.GetUserGuildsAsync(token); foreach (var guild in guilds) { // Get channels var channels = await _dataService.GetGuildChannelsAsync(token, guild.Id); // Get category channels var categoryChannels = channels.Where(c => c.Type == ChannelType.GuildCategory).ToArray(); // Get exportable channels var exportableChannels = channels.Where(c => c.Type.IsExportable()).ToArray(); // Create channel view models var channelViewModels = new List <ChannelViewModel>(); foreach (var channel in exportableChannels) { // Get category var category = categoryChannels.FirstOrDefault(c => c.Id == channel.ParentId)?.Name; // Create channel view model var channelViewModel = _viewModelFactory.CreateChannelViewModel(channel, category); // Add to list channelViewModels.Add(channelViewModel); } // Create guild view model var guildViewModel = _viewModelFactory.CreateGuildViewModel(guild, channelViewModels.OrderBy(c => c.Category) .ThenBy(c => c.Model.Name) .ToArray()); // Add to list availableGuilds.Add(guildViewModel); } // Update available guild list AvailableGuilds = availableGuilds; // Pre-select first guild SelectedGuild = AvailableGuilds.FirstOrDefault(); } catch (HttpErrorStatusCodeException ex) when(ex.StatusCode == HttpStatusCode.Unauthorized) { Notifications.Enqueue("Unauthorized – make sure the token is valid"); } catch (HttpErrorStatusCodeException ex) when(ex.StatusCode == HttpStatusCode.Forbidden) { Notifications.Enqueue("Forbidden – account may be locked by 2FA"); } finally { // Dispose progress operation operation.Dispose(); } }
/// <summary> /// Allows a token to be requested using basic login information /// </summary> public async Task <TaskResult <string> > RequestStandardToken(string email, string password) { UserEmail emailObj = await Context.UserEmails.FindAsync(email.ToLower()); if (emailObj == null) { return(new TaskResult <string>(false, "There was no user found with that email.", null)); } User user = await emailObj.GetUserAsync(); if (user.Disabled) { return(new TaskResult <string>(false, "Your account has been disabled.", null)); } bool authorized = false; if (!emailObj.Verified) { EmailConfirmCode confirmCode = await Context.EmailConfirmCodes.FindAsync(password); // Someone using another person's verification is a little // worrying, and we don't want them to know it worked, so we'll // send the same error either way. if (confirmCode == null || confirmCode.User_Id != user.Id) { return(new TaskResult <string>(false, "The email associated with this account needs to be verified! Please log in using the code " + "that was emailed as your password.", null)); } // At this point the email has been confirmed emailObj.Verified = true; Context.EmailConfirmCodes.Remove(confirmCode); await Context.SaveChangesAsync(); authorized = true; } else { var result = await UserManager.ValidateAsync(CredentialType.PASSWORD, email, password); if (result.Data != null && user.Id != result.Data.Id) { return(new TaskResult <string>(false, "A critical error occured. This should not be possible. Seek help immediately.", null)); } if (!result.Success) { Console.WriteLine($"Failed password validation for {email}"); return(new TaskResult <string>(false, result.Message, null)); } authorized = true; } // If the verification failed, forward the failure if (!authorized) { return(new TaskResult <string>(false, "Failed to authorize user.", null)); } // Check if there are any tokens already AuthToken token = null; token = await Context.AuthTokens.FirstOrDefaultAsync(x => x.App_Id == "VALOUR" && x.User_Id == user.Id && x.Scope == Permission.FullControl.Value); if (token == null) { // We now have to create a token for the user token = new AuthToken() { App_Id = "VALOUR", Id = Guid.NewGuid().ToString(), Time = DateTime.UtcNow, Expires = DateTime.UtcNow.AddDays(7), Scope = Permission.FullControl.Value, User_Id = user.Id }; using (ValourDB context = new ValourDB(ValourDB.DBOptions)) { await context.AuthTokens.AddAsync(token); await context.SaveChangesAsync(); } } else { token.Time = DateTime.UtcNow; token.Expires = DateTime.UtcNow.AddDays(7); using (ValourDB context = new ValourDB(ValourDB.DBOptions)) { context.AuthTokens.Update(token); await context.SaveChangesAsync(); } } return(new TaskResult <string>(true, "Successfully verified and retrieved token!", token.Id)); }
protected override void ProcessRecord() { if (ParameterSetName == CurrentSessionSet) { WriteObject(AuthenticatedCmdlet.SessionAuthToken); } else { AuthToken authToken = null; if (ParameterSetName == UserPasswordSet) { authToken = GetUserToken(); } else if (ParameterSetName == WindowsCredentialsSet) { authToken = GetWindowsToken(); } else if (ParameterSetName == UnauthenticatedSet) { authToken = GetUnauthenticatedToken(); } else if (ParameterSetName == CloudInteractiveSet || ParameterSetName == CloudCodeSet || ParameterSetName == CloudAPISet) { AuthToken token = null; if (Session.IsPresent) { token = AuthenticatedCmdlet.SessionAuthToken; } token = token ?? new AuthToken(); token.AuthorizationCode = AuthorizationCode; token.AuthorizationVerifier = AuthorizationVerifier; token.TenantName = TenantName; token.AccountName = AccountName; token.Token = null; token.AuthorizationRefreshToken = null; token.AuthorizationTokenId = null; token.AuthorizationUrl = AuthorizationUrl; token.AccountUrl = AccountUrl; token.ApplicationId = ApplicationId; if (ParameterSetName == CloudAPISet) { token.AuthorizationRefreshToken = UserKey; token.ApplicationId = ClientId; } token.CloudDeployment = string.IsNullOrWhiteSpace(CloudDeployment) ? CloudDeployments.Production : (CloudDeployments)Enum.Parse(typeof(CloudDeployments), CloudDeployment); if (ParameterSetName == CloudInteractiveSet) { token = GetInteractiveToken(token); } authToken = token; } GetServerVersion(authToken); if (!String.IsNullOrWhiteSpace(OrganizationUnit)) { SetOrganizationUnit(authToken, OrganizationUnit); } authToken.TenantName = authToken.TenantName ?? TenantName ?? "Default"; if (Session.IsPresent) { AuthenticatedCmdlet.SetAuthToken(authToken); } if (MyInvocation.BoundParameters.ContainsKey(nameof(RequestTimeout))) { authToken.RequestTimeout = RequestTimeout; } WriteObject(authToken); } }
/// <summary> /// Initializes a new instance of the <see cref="TradierHistoricalPricingCommand"/> class. /// </summary> /// <param name="token">The token.</param> internal TradierHistoricalPricingCommand(AuthToken token) : base(token?.BaseUrl, token?.AccessKey) { }
/** * 刷新access token (续期) * * @param authToken 登录成功后返回的Token信息 * @return AuthResponse */ public override AuthResponse Refresh(AuthToken authToken) { var token = getToken(RefreshTokenUrl(authToken.RefreshToken)); return(new AuthResponse(AuthResponseStatus.SUCCESS.GetCode(), AuthResponseStatus.SUCCESS.GetDesc(), token)); }
public void Authenticate(AuthToken token) { Authenticator = new JwtAuthenticator(token); }
public void Send(AuthToken token, Message message, string target) { Console.WriteLine($"Send message {message.Content}"); }
/// <summary> /// Initializes a new instance of the <see cref="TradierOptionExpirationCommand"/> class. /// </summary> /// <param name="token">The token.</param> /// <param name="symbol">The symbol.</param> internal TradierOptionExpirationCommand(AuthToken token, string symbol) : this(token) { Symbol = symbol; }
void IStreamCallbacks.RequestAuthTokenCallback(ErrorCode result, AuthToken authToken) { if (Error.Succeeded(result)) { // Now that the user is authorized the information can be requested about which server to stream to m_AuthToken = authToken; SetBroadcastState(BroadcastState.Authenticated); } else { m_AuthToken.Data = ""; SetBroadcastState(BroadcastState.Initialized); string err = Error.GetString(result); ReportError(string.Format("RequestAuthTokenDoneCallback got failure: {0}", err)); } try { if (AuthTokenRequestComplete != null) { this.AuthTokenRequestComplete(result, authToken); } } catch (Exception x) { ReportError(x.ToString()); } }
/// <summary> /// Formats the authentication header. /// </summary> /// <param name="authToken">Authentication token.</param> public override Tuple <string, string> FormatAuthHeader(AuthToken authToken) { // OMS API uses simple GUID as a client token return(Tuple.Create("clientToken", authToken.Token)); }
/// <summary> /// Sets the auth token to use if it has been saved from a previous session. If successful, this will proceed to log the user in /// and will fire LoginAttemptComplete with the result. /// </summary> /// <param name="username">The username</param> /// <param name="token">The AuthToken</param> /// <returns>Whether or not the auth token was set</returns> public virtual bool SetAuthToken(string username, AuthToken token) { if (this.IsIngestTesting) { return false; } Logout(); if (string.IsNullOrEmpty(username)) { ReportError("Username must be valid"); return false; } else if (token == null || token.Data[0] == '\0') { ReportError("Auth token must be valid"); return false; } m_UserName = username; m_AuthToken = token; if (this.IsInitialized) { SetBroadcastState(BroadcastState.Authenticated); } return true; }
public IHttpActionResult Login([FromBody] dynamic UserLog) { try { User user = new User(); if (UserLog.password.ToString() != "") { var password = UserLog.password.ToString(); if (UserLog.email.ToString() != "") { var email = UserLog.email.ToString(); try { try { _userServices.CheckIfActivated("email", email.ToString()); } catch (Exception ex) { return(Ok(new ErrorMessage(int.Parse(ex.Message)))); } user = _userRepository.GetByEmail(email); var username = user.Username; if (user.Password == password) { var token = AuthToken.CreateJwt(username, email, UserTypesClass.Convert(user.Type), 450000000); return(Ok(token)); } } catch (UserException ex) { return(Ok(new ErrorMessage(int.Parse(ex.Message)))); } } else if (UserLog.username.ToString() != "") { var username = UserLog.username.ToString(); try { _userServices.CheckIfActivated("username", username.ToString()); user = _userRepository.GetByUsername(username); if (user.Password == password) { var token = AuthToken.CreateJwt(username.ToString(), user.Email, UserTypesClass.Convert(user.Type), 450000000); return(Ok(token)); } } catch (UserException ex) { return(Ok(new ErrorMessage(int.Parse(ex.Message)))); } } else { return(Ok(new ErrorMessage(701))); } } else { return(Ok(new ErrorMessage(703))); } return(Ok(new ErrorMessage(702))); } catch { return(Ok(new ErrorMessage(101))); } }
public Topics(AuthToken authToken) { _authToken = authToken; }
public AuthController(IConfiguration config) { auth = new AuthToken(config); }
protected override void SolveInstance(IGH_DataAccess DA) { //declare input variables to load into AuthToken authToken = new AuthToken(); string sheetName = ""; string worksheet = ""; bool rowsColumns = false; GH_Structure<GH_String> addresses = new GH_Structure<GH_String>(); GH_Structure<GH_String> data = new GH_Structure<GH_String>(); bool write = false; //declare output variables GH_Structure<GH_String> addressesOut = new GH_Structure<GH_String>(); //get data from inputs if (!DA.GetData<AuthToken>("Token", ref authToken)) { return; //exit if no token given } if (!authToken.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The provided authentication token appears to be invalid. Try re-running the Google Authenticator component."); return; //exit if token invalid } if (!DA.GetData<string>("Name", ref sheetName)) { return; //exit if no name given } DA.GetData<string>("Worksheet", ref worksheet); DA.GetData<bool>("Organize by Rows or Columns", ref rowsColumns); DA.GetDataTree<GH_String>("Address", out addresses); DA.GetDataTree<GH_String>("Data", out data); DA.GetData<bool>("Write", ref write); if (!write) return; //exit if write is not true //check each specified address for validity foreach (GH_String address in addresses.AllData(true)) { if (!GDriveUtil.isValidAddress(address.ToString())) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error,"Not all addresses are specified in a valid format."); return; } } //setup auth and factory //set up oAuth parameters OAuth2Parameters parameters = GDriveUtil.GetParameters(authToken); SpreadsheetsService service = GDriveUtil.GetSpreadsheetsService(parameters); //find spreadsheet by name SpreadsheetEntry spreadsheet = GDriveUtil.findSpreadsheetByName(sheetName, service); if (spreadsheet == null) //if the spreadsheet is not found { if (createNewSpreadsheets) //if the user has elected to create new spreadsheets { List<string> worksheets = new List<string>(); if (!String.IsNullOrEmpty(worksheet)) { worksheets.Add(worksheet); //create a 1-item list with the worksheet name } spreadsheet = CreateSpreadsheet.createNewSpreadsheet(this, authToken, sheetName, worksheets, false); //create the spreadsheet } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified spreadsheet not found."); return; } } //find worksheet by name WorksheetEntry worksheetEntry = GDriveUtil.findWorksheetByName(worksheet, spreadsheet); if (worksheetEntry == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified worksheet not found."); return; } uint maxRow = 0; uint maxCol = 0; // set up dictionary<Cell address, cell input> // associate each input value with a corresponding address Dictionary<string, string> writeMap = constructWriteMap(addresses, data, rowsColumns, ref maxRow, ref maxCol, ref addressesOut); //expand worksheet if necessary if (worksheetEntry.Rows < maxRow) { worksheetEntry.Rows = maxRow; worksheetEntry.Etag = "*"; //required for compatibility with "new" google sheets (see: http://stackoverflow.com/questions/22719170/updating-cell-in-google-spreadsheets-returns-error-missing-resource-version-id) worksheetEntry.Update(); } if (worksheetEntry.Cols < maxCol) { worksheetEntry.Cols = maxCol; worksheetEntry.Etag = "*"; //required for compatibility with "new" google sheets (see: http://stackoverflow.com/questions/22719170/updating-cell-in-google-spreadsheets-returns-error-missing-resource-version-id) worksheetEntry.Update(); } //set bounds of cell query CellQuery cellQuery = new CellQuery(worksheetEntry.CellFeedLink); cellQuery.MinimumColumn = 0; cellQuery.MinimumRow = 0; cellQuery.MaximumColumn = maxCol; cellQuery.MaximumRow = maxRow; cellQuery.ReturnEmpty = ReturnEmptyCells.yes; //retrieve cellfeed CellFeed cellFeed = service.Query(cellQuery); //convert cell entries to dictionary Dictionary<string,AtomEntry> cellDict = cellFeed.Entries.ToDictionary(k => k.Title.Text); CellFeed batchRequest = new CellFeed(cellQuery.Uri, service); //set up batchrequest foreach (KeyValuePair<string, string> entry in writeMap) { AtomEntry atomEntry; cellDict.TryGetValue(entry.Key, out atomEntry); CellEntry batchEntry = atomEntry as CellEntry; batchEntry.InputValue = entry.Value; batchEntry.Etag = "*"; //required for compatibility with "new" google sheets (see: http://stackoverflow.com/questions/22719170/updating-cell-in-google-spreadsheets-returns-error-missing-resource-version-id) batchEntry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.update); batchRequest.Entries.Add(batchEntry); } CellFeed batchResponse = (CellFeed)service.Batch(batchRequest, new Uri(cellFeed.Batch)); // Check the results bool isSuccess = true; foreach (CellEntry entry in batchResponse.Entries) { string batchId = entry.BatchData.Id; if (entry.BatchData.Status.Code != 200) { isSuccess = false; GDataBatchStatus status = entry.BatchData.Status; } } if (!isSuccess) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Update operations failed"); } //output addresses DA.SetDataTree(0, addressesOut); //write addressesOut to first output parameter }
/// <summary> /// Logs the current user out and clear the username and auth token. This will terminate the broadcast if necessary. /// </summary> /// <returns>Whether or not successfully logged out</returns> public virtual bool Logout() { if (this.IsIngestTesting) { return false; } // stop synchronously if (this.IsBroadcasting) { m_Stream.Stop(false); } m_UserName = ""; m_AuthToken = new AuthToken(); if (!m_LoggedIn) { return false; } m_LoggedIn = false; // only fire the event if the logout was explicitly requested if (!m_ShuttingDown) { try { if (LoggedOut != null) { this.LoggedOut(); } } catch (Exception x) { ReportError(x.ToString()); } } SetBroadcastState(BroadcastState.Initialized); return true; }
private void UpdateAuthToken(AuthToken authToken) { authToken.LastAccessTime = DateTime.Now; _appContext.Entry(authToken).State = EntityState.Modified; _appContext.SaveChanges(); }
protected override void SolveInstance(IGH_DataAccess DA) { //declare input variables to load into AuthToken authToken = new AuthToken(); string sheetName = ""; string worksheet = ""; bool includeBlankCells = false; bool rangeSpecified = false; SpreadsheetRange range = new SpreadsheetRange(); bool rowsColumns = false; bool formulasValues = false; //declare output variables List<string> metaData = new List<string>(); GH_Structure<GH_String> values = new GH_Structure<GH_String>(); GH_Structure<GH_String> addresses = new GH_Structure<GH_String>(); //get data from inputs if (!DA.GetData<AuthToken>("Token", ref authToken)) { return; //exit if no token } if (!authToken.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The provided authentication token appears to be invalid. Try re-running the Google Authenticator component."); return; //exit if invalid token } if (!DA.GetData<string>("Name", ref sheetName)) { return; //exit if no name provided } DA.GetData<string>("Worksheet", ref worksheet); DA.GetData<bool>("Include Blank Cells?", ref includeBlankCells); if (DA.GetData<SpreadsheetRange>("Spreadsheet Range", ref range)) { rangeSpecified = true; } DA.GetData<bool>("Organize by Rows or Columns", ref rowsColumns); DA.GetData<bool>("Read Formulas or Values", ref formulasValues); //set up oAuth parameters OAuth2Parameters parameters = GDriveUtil.GetParameters(authToken); //establish spreadsheetservice SpreadsheetsService service = GDriveUtil.GetSpreadsheetsService(parameters); //get spreadsheet by name SpreadsheetEntry spreadsheet = GDriveUtil.findSpreadsheetByName(sheetName, service); if (spreadsheet == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified Spreadsheet not found."); return; } //gather spreadsheet metadata metaData.Add("Spreadsheet Name: " + spreadsheet.Title.Text); metaData.Add("Last Updated: " + spreadsheet.Updated.ToString()); metaData.Add("Worksheets: " + worksheetList(spreadsheet.Worksheets)); //find the specified worksheet, or first one if none specified WorksheetEntry worksheetEntry = null; worksheetEntry = GDriveUtil.findWorksheetByName(worksheet, spreadsheet); if (worksheetEntry == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specified worksheet not found."); return; } // Fetch the cell feed of the worksheet. CellQuery cellQuery = new CellQuery(worksheetEntry.CellFeedLink); if (rangeSpecified) { if (range.TestValid()) { cellQuery.MinimumColumn = range.startColumn(); cellQuery.MinimumRow = range.startRow(); cellQuery.MaximumColumn = range.endColumn(); cellQuery.MaximumRow = range.endRow(); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid Range Specified"); return; } } //passes null values if user wants the blank cells represented, otherwise they are omitted from output. if (includeBlankCells) { cellQuery.ReturnEmpty = ReturnEmptyCells.yes; } //set up cell feed CellFeed cellFeed = service.Query(cellQuery); foreach (CellEntry cell in cellFeed.Entries) //for all the cells in the feed { GH_Path path = new GH_Path(DA.Iteration); //set up data path for data tree uint e = (rowsColumns) ? cell.Row : cell.Column; //decide whether to structure data path by row or column path = path.AppendElement((int)e); string v = (formulasValues) ? cell.InputValue : cell.Value; //decide whether to get the cell formula or the cell value as output values.Append(new GH_String(v), path); //save the value of the cell addresses.Append(new GH_String(cell.Title.Text), path); // save the address of the cell } //set output data DA.SetDataTree(0, values); DA.SetDataTree(1, addresses); DA.SetDataList("Sheet Info", metaData); }
public async Task <AccountDto> Registration(AccountDto accountDto, string secret) { Account account = dbContext.Accounts .Where(a => a.PhoneNumber == accountDto.PhoneNumber && a.CallingCountryCode == accountDto.CallingCountryCode) .SingleOrDefault(); if (account != null) { return(null); } account = new Account { Firstname = accountDto.Firstname, Lastname = accountDto.Lastname, Email = accountDto.Email, PhoneNumber = accountDto.PhoneNumber, CallingCodeObj = await dbContext.CallingCode.Where(cc => cc.CallingCountryCode == accountDto.CallingCountryCode).SingleOrDefaultAsync() }; if (accountDto.Contacts?.Count > 0) { // add as contacts those accounts that exist (TODO: Change to consider country prefix and possible '0' infront of phone number) var dtoContacts = accountDto.Contacts.Select(dto => dto.ContactPhoneNumber).ToList(); List <Account> contactsToAdd = dbContext.Accounts .Where(a => dtoContacts.Contains(a.PhoneNumber)) .ToList(); account.Contacts = contactsToAdd.Select(a => new Contact { Account = account, ContactAccountId = a.Id, ContactName = accountDto.Contacts.SingleOrDefault(c => c.ContactPhoneNumber == a.PhoneNumber)?.ContactName }) .ToList(); } // TODO: Generate a Token (on Prod this will be a phone/sms code confirmation ~ on Dev think about how to implement this) var token = new AuthToken { Account = account, Value = JWTokenHandler.GenerateToken(account.PhoneNumber, secret) }; dbContext.Accounts.Add(account); dbContext.AuthTokens.Add(token); await dbContext.SaveChangesAsync(); return(new AccountDto { Firstname = account.Firstname, Lastname = account.Lastname, Email = account.Email, PhoneNumber = account.PhoneNumber, CallingCountryCode = account.CallingCodeObj.CallingCountryCode, DateRegistered = account.DateRegistered, Token = token.Value, CreateSession = true, Contacts = account.Contacts?.Select(c => new ContactDto { DateAdded = c.DateAdded, ContactName = c.ContactName, AvatarImageUrl = c.ContactAccount.AvatarImageUrl, CoverImageUrl = c.ContactAccount.CoverImageUrl, ContactPhoneNumber = c.ContactAccount.PhoneNumber, ContactAccountId = c.ContactAccountId }).ToList() }); }
private async Task SetToken(AuthToken token) { if (token.ExpiresIn > DateTime.Now) { await Context.SetToken(token); Save(); SuccessAction?.Invoke(token); this.Hide(); } }
protected override void ProcessRecord() { if (ParameterSetName == CurrentSessionSet) { WriteObject(AuthenticatedCmdlet.SessionAuthToken); } else { AuthToken authToken = null; if (Host.IsPresent) { TenantName = "Host"; } if (!string.IsNullOrWhiteSpace(URL)) { var uri = new Uri(URL); if (0 == string.Compare(uri.Host, "alpha.uipath.com", true) || 0 == string.Compare(uri.Host, "staging.uipath.com", true) || 0 == string.Compare(uri.Host, "cloud.uipath.com", true) || 0 == string.Compare(uri.Host, "platform.uipath.com", true)) { WriteError("Use -CloudDeployment parameter to connect to UiPath Automation Cloud"); return; } } if (ParameterSetName == UserPasswordSet || ParameterSetName == HostSet) { authToken = GetUserToken(); } else if (ParameterSetName == WindowsCredentialsSet) { authToken = GetWindowsToken(); } else if (ParameterSetName == UnauthenticatedSet) { authToken = GetUnauthenticatedToken(); } else if (ParameterSetName == CloudAPISet) { AuthToken token = null; if (Session.IsPresent) { token = AuthenticatedCmdlet.SessionAuthToken; } token = token ?? new AuthToken(); token.TenantName = TenantName; token.AccountName = AccountName; token.Token = null; token.AuthorizationRefreshToken = null; if (ParameterSetName == CloudAPISet) { token.AuthorizationRefreshToken = UserKey; token.ApplicationId = ClientId; } token.CloudDeployment = string.IsNullOrWhiteSpace(CloudDeployment) ? CloudDeployments.Production : (CloudDeployments)Enum.Parse(typeof(CloudDeployments), CloudDeployment); authToken = token; } GetServerVersion(authToken); authToken.TenantName = authToken.TenantName ?? TenantName; if (!string.IsNullOrWhiteSpace(OrganizationUnit)) { if (authToken.ApiVersion >= OrchestratorProtocolVersion.V19_10) { WriteWarning("The use of OrganizationUnit is deprecated and will be removed. Use FolderPath instead."); } SetOrganizationUnit(authToken, OrganizationUnit); } else if (!string.IsNullOrWhiteSpace(FolderPath)) { if (authToken.ApiVersion < OrchestratorProtocolVersion.V19_10) { WriteError("Use of FolderPath requires Orchestrator version 19.10 or newer."); } SetCurrentFolder(authToken, FolderPath, Timeout); } else if (authToken.ApiVersion >= OrchestratorProtocolVersion.V19_10 && 0 != string.Compare(TenantName, "Host", true) && !Host.IsPresent) { FindAndSetDefaultFolder(authToken, Timeout); WriteVerbose($"No FolderPath was specified, using {authToken.CurrentFolder?.DisplayName}"); } else { authToken.CurrentFolder = default; authToken.OrganizationUnit = default; authToken.OrganizationUnitId = default; } if (Session.IsPresent) { AuthenticatedCmdlet.SetAuthToken(authToken); } if (MyInvocation.BoundParameters.ContainsKey(nameof(RequestTimeout))) { authToken.RequestTimeout = RequestTimeout; } WriteObject(authToken); } }
//gets the OAuth parameters from a given Auth Token public static OAuth2Parameters GetParameters(AuthToken authToken) { OAuth2Parameters parameters = GetParameters(); parameters.AccessToken = authToken.Token; parameters.RefreshToken = authToken.RefreshToken; return parameters; }
public static IList<string> List(AuthToken authToken) { try { throw new NotImplementedException(); //return new List<string>(); } catch (Exception ex) { throw ex; //return null; } }