internal ApiKey(UserApiKey nativeKey) { Id = nativeKey.Id; Name = nativeKey.Name; Value = nativeKey.Key; IsEnabled = !nativeKey.disabled; }
public UserApiKey GenerateApiKeys(Guid id) { var user = _context.Users.Find(id); if (user == null) { return(null); } var existingActiveKeys = _context.ApiKeys.Where(key => key.User == user && key.Active).ToList(); if (existingActiveKeys.Count > 0) { // disable any active keys foreach (var activeKey in existingActiveKeys) { activeKey.Active = false; } } var newKey = new UserApiKey { PublicKey = GenerateKey(24), PrivateKey = GenerateKey(48), User = user, UserId = user.Id, Active = true, Generated = DateTime.Now }; _context.ApiKeys.Add(newKey); _context.SaveChanges(); return(newKey); }
private static unsafe void HandleApiKeysCallback(IntPtr tcs_ptr, IntPtr api_keys, int api_keys_len, AppError error) { var tcsHandle = GCHandle.FromIntPtr(tcs_ptr); try { var tcs = (TaskCompletionSource <UserApiKey[]>)tcsHandle.Target; if (error.is_null) { var result = new UserApiKey[api_keys_len]; for (var i = 0; i < api_keys_len; i++) { result[i] = Marshal.PtrToStructure <UserApiKey>(IntPtr.Add(api_keys, i * UserApiKey.Size)); } tcs.TrySetResult(result); } else { tcs.TrySetException(new AppException(error)); } } finally { tcsHandle.Free(); } }
/// <summary> /// Get the list of ApiKey entities owned by en-user /// </summary> /// <param name="userId">Id of the user for whome new key will be issued</param> /// <param name="description">Descritpion of an API key to be created</param> /// <returns></returns> public UserApiKey CreateUserApiKey(string userId, string description) { UserApiKey newKey = UserApiKey.CreateNew(_userRepository.GetById(new Guid(userId)), description); _userApiKeyRepository.Add(newKey); _userRepository.SaveChanges(); return(_userApiKeyRepository.GetById(newKey.Id)); }
public virtual UserApiKey ToModel(UserApiKey apiKey) { if (apiKey == null) { throw new ArgumentNullException(nameof(apiKey)); } apiKey.Id = Id; apiKey.ApiKey = ApiKey; apiKey.UserName = UserName; apiKey.UserId = UserId; apiKey.IsActive = IsActive; return(apiKey); }
/// <summary> /// Delete an API key by its Id /// </summary> /// <param name="apiKeyId">Id of the API key to be deleted</param> /// <returns>True if key was deleted. Otherwise false</returns> public bool DeleteUserApiKey(string apiKeyId) { bool result = false; UserApiKey apiKey = _userApiKeyRepository.GetById(new Guid(apiKeyId)); if (null != apiKey) { _userApiKeyRepository.Delete(apiKey); _userApiKeyRepository.SaveChanges(); result = true; } return(result); }
public async Task <CreateUserApiKeyResult> CreateApiKey(object userId, string name, string description) { var apiKey = new UserApiKey() { UserId = userId.ToString(), Name = name, Description = description }; string privateKey; apiKey.ApiKey = this.asymmetricCryptoProvider.GenerateKeys(out privateKey); return(new CreateUserApiKeyResult() { ApiKey = apiKey, PrivateKey = privateKey }); }
public virtual UserApiKeyEntity FromModel(UserApiKey apiKey, PrimaryKeyResolvingMap pkMap) { if (apiKey == null) { throw new ArgumentNullException(nameof(apiKey)); } pkMap.AddPair(apiKey, this); Id = apiKey.Id; ApiKey = apiKey.ApiKey; UserName = apiKey.UserName; UserId = apiKey.UserId; IsActive = apiKey.IsActive; return(this); }
public ApiEntityPage <UserApiKeyJsonEntity> CreateApiKey([FromBody] IDictionary <string, string> requestBody) { // In general it is not a good idea to parse JSON object into the dictionary, // but here we need to have only on field with description, so there is // no need to create an object. Maybe in the fitire when we decide to have // mode fields here - we will convert this to a normal input object. string keyDescription = requestBody.ContainsKey("description") ? requestBody["description"] : "not set"; UserApiKey apiKey = _userService.CreateUserApiKey(UserId, keyDescription); // Convreting to fancy JSON ApiEntityPage <UserApiKeyJsonEntity> result = new ApiEntityPage <UserApiKeyJsonEntity>(new UserApiKeyJsonEntity(apiKey), Request.Path.ToString()); Response.StatusCode = StatusCodes.Status201Created; return(result); }
/// <summary> /// 创建一个apikey /// </summary> /// <param name="openid"></param> /// <returns></returns> private string CreateApiKey(string openid) { var data = dbContext.UserApiKeys.FirstOrDefault(x => x.OpenId == openid); if (data != null) { return(data.ApiKey); } else { var userkey = new UserApiKey() { //用guid随机生成一个 ApiKey = Guid.NewGuid().ToString().Replace("-", ""), OpenId = openid }; dbContext.UserApiKeys.Add(userkey); dbContext.SaveChanges(); return(userkey.ApiKey); } }
public async Task <ApiSecretInfo> Generate(Guid userId) { var apiKey = new UserApiKey() { DateCreated = DateTime.UtcNow, IsActive = true, ApiKey = RandomUtils.GetRandomString(32), ApiSecret = RandomUtils.GetRandomString(64), UserId = userId }; context.UserApiKeys.Add(apiKey); await context.SaveChangesAsync(); return(new ApiSecretInfo() { ApiKey = apiKey.ApiKey, ApiSecret = apiKey.ApiSecret, IsActive = apiKey.IsActive }); }
public bool AddApiKey(int userId, string apiKey) { var dbUser = _db.UserRepository.GetById(userId); if (dbUser == null) { return(false); } var dbSession = new UserApiKey() { UserId = userId, ApiKey = apiKey, ExpirationDateTime = DateTime.UtcNow.AddMinutes(15), IsActive = true, User = dbUser }; _db.UserApiKeyRepository.Insert(dbSession); _db.Save(); return(true); }
/// <summary>Creates an API key.</summary> /// <param name="userId">Identifier for the user.</param> /// <param name="name">The name.</param> /// <param name="description">The description.</param> /// <returns>The new API key.</returns> public override async Task <CreateUserApiKeyResult> CreateApiKey(object userId, string name, string description) { var apiKey = new UserApiKey() { UserId = userId.ToString(), Name = name, Description = description }; string privateKey; apiKey.ApiKey = this.AsymmetricCryptoProvider.GenerateKeys(out privateKey); var result = await this.UserApiKeyRepository.Create(apiKey); if (result != null) { return(new CreateUserApiKeyResult() { ApiKey = result, PrivateKey = privateKey }); } return(null); }
public SessionServer(Id id, SessionToken sessionToken, UserApiKey userApiKey) { Id = id; SessionToken = sessionToken; UserApiKey = userApiKey; }
//------------------------------------------------------------------------------------------------------------------------ public ApiKeyInfoTimelineInfo(API.Warlock.ApiKeyDescriptor desc) { UserApiKey = desc.UserApiKey; Name = desc.Name; Type = desc.Type; }
public Task <ActionResult <UserApiKey[]> > UpdateUserApiKey([FromBody] UserApiKey userApiKey) { return(SaveUserApiKey(userApiKey)); }
public async Task <ActionResult <UserApiKey[]> > SaveUserApiKey([FromBody] UserApiKey userApiKey) { await _userApiKeyService.SaveApiKeysAsync(new[] { userApiKey }); return(Ok()); }
/// <summary> /// Default costructor from actual model entity /// </summary> public UserApiKeyJsonEntity(UserApiKey apiKey) { Id = apiKey.Id.ToString(); Key = apiKey.APIKey; Description = apiKey.Description; }
/// <summary> /// Handler for Auth async ovveride /// </summary> /// <returns></returns> protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { if (Request.Path.HasValue && Request.Path.Value.ToLower().Equals(Options.LoginPath)) { return(AuthenticateResult.NoResult()); } if (!Request.Headers.TryGetValue(HeaderNames.Authorization, out var authorization)) { return(AuthenticateResult.Fail("Request was not archestrated with proper Authorization header")); } if (string.IsNullOrEmpty(authorization)) { //TODO: Credentials are missing. Maybe we need to act here somehow return(AuthenticateResult.Fail("Authorization header is empty or malformed")); } if (((string)authorization)?.Split(' ').Length != 2) { //TODO: Credentials are missing. Maybe we need to act here somehow return(AuthenticateResult.Fail("Authorization header is malformed. Expected structure is '<schema> <value>'")); } IServiceProvider serviceProvider = Request.HttpContext.RequestServices; UserService userService = serviceProvider.GetService <UserService>(); Guid userId = default(Guid); try { string schema = ((string)authorization)?.Split(' ', 2)[0]; string token = ((string)authorization)?.Split(' ', 2)[1]; if (String.Equals(schema, CustomAuthOptions.DefaultSchema, StringComparison.OrdinalIgnoreCase)) { UserToken userToken = await userService.GetByTokenAsync(token); if (userToken == null || userToken.IsTokenExpired()) { return(AuthenticateResult.Fail("Authorization header contains invalid token")); } await userService.ShiftTokenAsync(userToken); userId = userToken.UserId; Options.Schema = CustomAuthOptions.DefaultSchema; } else if (String.Equals(schema, CustomAuthOptions.ApiKeyScheme, StringComparison.OrdinalIgnoreCase)) { UserApiKey userApiKey = await userService.GetByApiKeyAsync(token); if (userApiKey == null) { return(AuthenticateResult.Fail("Authorization header contains invalid API key")); } userId = userApiKey.UserId; Options.Schema = CustomAuthOptions.ApiKeyScheme; } else { return(AuthenticateResult.Fail("Authorization header contains unknows schema")); } } catch (Exception ex) { return(AuthenticateResult.Fail($"Auth failed: {ex.Message}")); } List <Claim> claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, userId.ToString()) }; List <ClaimsIdentity> identities = new List <ClaimsIdentity> { new ClaimsIdentity(claims, Options.Schema) }; AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(identities), Options.Schema); return(AuthenticateResult.Success(ticket)); }