public void Update(DestinyPostGameCarnageReportData?other) { if (other is null) { return; } if (Period != other.Period) { Period = other.Period; OnPropertyChanged(nameof(Period)); } if (StartingPhaseIndex != other.StartingPhaseIndex) { StartingPhaseIndex = other.StartingPhaseIndex; OnPropertyChanged(nameof(StartingPhaseIndex)); } if (!ActivityDetails.DeepEquals(other.ActivityDetails)) { ActivityDetails.Update(other.ActivityDetails); OnPropertyChanged(nameof(ActivityDetails)); } if (!Entries.DeepEqualsList(other.Entries)) { Entries = other.Entries; OnPropertyChanged(nameof(Entries)); } if (!Teams.DeepEqualsList(other.Teams)) { Teams = other.Teams; OnPropertyChanged(nameof(Teams)); } }
public void SuccessfulShareShouldReturnCorrectValues() { const string wrappedReceiptKey = "kyHPjq2+Y48cx+9yS/XzmW09jVUylSdhbP+3Q9Tc9p6bCEnyfa8vj38AIu744RzzE+Dc4qkSF21VfzQKtJVILfOXu5xRc7MYa5k3zWhjiesg/gsrv7J4wDyyBpHIJB8TWXnubYMbSYQJjlsfwyxE9kGe0YI08pRo2Tiht0bfR5Z/YrhAk4UBvjp84D+oyug/1mtGhKphA4vgPhQ9/y2wcInYxju7Q6yzOsXGaRUXR38Tn2YmY9OBgjxiTnhoYJFP1X9YJkHeWMW0vxF1RHxgIVrpf7oRzdY1nq28qzRg5+wC7cjRpS2i/CKUAo0oVG4pbpXsaFhaTewStVC7UFtA77JHb3EnF4HcSWMnK5FM7GGkL9MMXQenh11NZHKPWXpux0nLZ6/vwffXZfsiyTIcFL/NajGN8C/hnNBljoQ+B3fzWbjcq5ueUOPwARZ1y38W83UwMynzkud/iEdHLaZIu4qUCRkfSxJg7Dc+O9/BdiffkOn2GyFmNjVeq754DCUypxzMkjYxokedN84nK13OU4afVyC7t5DDxAK/MqAc69NCBRLqMi5f8BMeOZfMcSWPGC9a2Qu8VgG125TuZT4+wIykUhGyj3Bb2/fdPsxwuKFR+E0uqs0ZKvcv1tkNRRtKYBqTacgGK9Yoehg12cyLrITLdjU1fmIDn4/vrhztN5w="; const string otherPartyProfileContent = "ChCZAib1TBm9Q5GYfFrS1ep9EnAwQB5shpAPWLBgZgFgt6bCG3S5qmZHhrqUbQr3yL6yeLIDwbM7x4nuT/MYp+LDXgmFTLQNYbDTzrEzqNuO2ZPn9Kpg+xpbm9XtP7ZLw3Ep2BCmSqtnll/OdxAqLb4DTN4/wWdrjnFC+L/oQEECu646"; const string rememberMeId = "remember_me_id0123456789"; const string parentRememberMeId = "parent_remember_me_id0123456789"; const string receiptId = "receipt_id_123"; Mock <HttpMessageHandler> handlerMock = SetupMockMessageHandler( HttpStatusCode.OK, "{\"receipt\":{\"wrapped_receipt_key\": \"" + wrappedReceiptKey + "\",\"other_party_profile_content\": \"" + otherPartyProfileContent + "\",\"remember_me_id\":\"" + rememberMeId + "\",\"parent_remember_me_id\":\"" + parentRememberMeId + "\",\"receipt_id\":\"" + receiptId + "\", \"sharing_outcome\":\"SUCCESS\", \"timestamp\":\"2016-01-01T00:00:00Z\"}}"); var engine = new YotiClientEngine(new HttpClient(handlerMock.Object)); ActivityDetails activityDetails = engine.GetActivityDetailsAsync(EncryptedToken, SdkId, _keyPair, new Uri(Constants.Api.DefaultYotiApiUrl)).Result; Assert.IsNotNull(activityDetails); Assert.IsNotNull(activityDetails.Profile); Assert.AreEqual(receiptId, activityDetails.ReceiptId); Assert.AreEqual(rememberMeId, activityDetails.RememberMeId); Assert.AreEqual(parentRememberMeId, activityDetails.ParentRememberMeId); Assert.IsNull(activityDetails.ExtraData.AttributeIssuanceDetails); Assert.AreEqual(new DateTime(2016, 1, 1, 0, 0, 0), activityDetails.Timestamp); Assert.IsNotNull(activityDetails.Profile.Selfie); Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("selfie0123456789")), Convert.ToBase64String(activityDetails.Profile.Selfie.GetValue().GetContent())); Assert.AreEqual("phone_number0123456789", activityDetails.Profile.MobileNumber.GetValue()); Assert.AreEqual(new DateTime(1980, 1, 1), activityDetails.Profile.DateOfBirth.GetValue()); }
public Result <ActivityDetails> SetTurnDisabled(int turnId, int byUserId, bool disabled) { var turn = _db.Turns.Find(turnId); if (turn != null) { if (turn.IsDisabled != disabled) { turn.IsDisabled = disabled; turn.ModifierId = byUserId; var activity = GetActivity(turn.ActivityId, false, true); if (activity == null) { return(Result.Failure <ActivityDetails>("no such activity")); } var details = ActivityDetails.Calculate(activity, byUserId, _mapper); _db.Entry(activity).State = EntityState.Modified; _db.SaveChanges(); details.Update(activity); return(Result.Success(details)); } return(Result.Success(GetActivityDetails(turn.ActivityId, byUserId))); } return(Result.Failure <ActivityDetails>("Invalid turn id")); }
public bool Equals(DestinyPostGameCarnageReportData input) { if (input == null) { return(false); } return (( Period == input.Period || (Period != null && Period.Equals(input.Period)) ) && ( StartingPhaseIndex == input.StartingPhaseIndex || (StartingPhaseIndex.Equals(input.StartingPhaseIndex)) ) && ( ActivityDetails == input.ActivityDetails || (ActivityDetails != null && ActivityDetails.Equals(input.ActivityDetails)) ) && ( Entries == input.Entries || (Entries != null && Entries.SequenceEqual(input.Entries)) ) && ( Teams == input.Teams || (Teams != null && Teams.SequenceEqual(input.Teams)) )); }
public bool DeepEquals(DestinyHistoricalStatsPeriodGroup?other) { return(other is not null && Period == other.Period && (ActivityDetails is not null ? ActivityDetails.DeepEquals(other.ActivityDetails) : other.ActivityDetails is null) && Values.DeepEqualsDictionary(other.Values)); }
public async Task YotiClient_GetActivityDetailsAsync() { YotiClient client = CreateYotiClient(); ActivityDetails activityDetails = await client.GetActivityDetailsAsync(encryptedToken); Assert.IsNotNull(activityDetails.Outcome); }
public void YotiClient_GetActivityDetails() { YotiClient client = CreateYotiClient(); ActivityDetails activityDetails = client.GetActivityDetails(encryptedToken); Assert.IsNotNull(activityDetails.Outcome); }
public bool DeepEquals(DestinyPostGameCarnageReportData?other) { return(other is not null && Period == other.Period && StartingPhaseIndex == other.StartingPhaseIndex && (ActivityDetails is not null ? ActivityDetails.DeepEquals(other.ActivityDetails) : other.ActivityDetails is null) && Entries.DeepEqualsList(other.Entries) && Teams.DeepEqualsList(other.Teams)); }
// GET: Account/Connect?token public ActionResult Connect(string token) { if (token == null) { return(RedirectToAction("Index", "Home")); } try { string sdkId = Environment.GetEnvironmentVariable("YOTI_CLIENT_SDK_ID"); _logger.LogInformation(string.Format("sdkId='{0}'", sdkId)); string yotiKeyFilePath = Environment.GetEnvironmentVariable("YOTI_KEY_FILE_PATH"); _logger.LogInformation( string.Format( "yotiKeyFilePath='{0}'", yotiKeyFilePath)); StreamReader privateKeyStream = System.IO.File.OpenText(yotiKeyFilePath); var yotiClient = new YotiClient(sdkId, privateKeyStream); ActivityDetails activityDetails = yotiClient.GetActivityDetails(token); var profile = activityDetails.Profile; ViewBag.RememberMeID = activityDetails.RememberMeId; DisplayAttributes displayAttributes = CreateDisplayAttributes(profile.AttributeCollection); if (profile.FullName != null) { displayAttributes.FullName = profile.FullName.GetValue(); } YotiAttribute <Image> selfie = profile.Selfie; if (profile.Selfie != null) { displayAttributes.Base64Selfie = selfie.GetValue().GetBase64URI(); } return(View(displayAttributes)); } catch (Exception e) { _logger.LogError( exception: e, message: e.Message); TempData["Error"] = e.Message; TempData["InnerException"] = e.InnerException?.Message; return(RedirectToAction("Error")); } }
public void ShouldAddAuthKeyHeaderToProfileRequest() { Mock <HttpMessageHandler> handlerMock = SetupMockMessageHandler( HttpStatusCode.OK, "{\"receipt\":{\"wrapped_receipt_key\": \"kyHPjq2+Y48cx+9yS/XzmW09jVUylSdhbP+3Q9Tc9p6bCEnyfa8vj38AIu744RzzE+Dc4qkSF21VfzQKtJVILfOXu5xRc7MYa5k3zWhjiesg/gsrv7J4wDyyBpHIJB8TWXnubYMbSYQJjlsfwyxE9kGe0YI08pRo2Tiht0bfR5Z/YrhAk4UBvjp84D+oyug/1mtGhKphA4vgPhQ9/y2wcInYxju7Q6yzOsXGaRUXR38Tn2YmY9OBgjxiTnhoYJFP1X9YJkHeWMW0vxF1RHxgIVrpf7oRzdY1nq28qzRg5+wC7cjRpS2i/CKUAo0oVG4pbpXsaFhaTewStVC7UFtA77JHb3EnF4HcSWMnK5FM7GGkL9MMXQenh11NZHKPWXpux0nLZ6/vwffXZfsiyTIcFL/NajGN8C/hnNBljoQ+B3fzWbjcq5ueUOPwARZ1y38W83UwMynzkud/iEdHLaZIu4qUCRkfSxJg7Dc+O9/BdiffkOn2GyFmNjVeq754DCUypxzMkjYxokedN84nK13OU4afVyC7t5DDxAK/MqAc69NCBRLqMi5f8BMeOZfMcSWPGC9a2Qu8VgG125TuZT4+wIykUhGyj3Bb2/fdPsxwuKFR+E0uqs0ZKvcv1tkNRRtKYBqTacgGK9Yoehg12cyLrITLdjU1fmIDn4/vrhztN5w=\",\"other_party_profile_content\": \"ChCZAib1TBm9Q5GYfFrS1ep9EnAwQB5shpAPWLBgZgFgt6bCG3S5qmZHhrqUbQr3yL6yeLIDwbM7x4nuT/MYp+LDXgmFTLQNYbDTzrEzqNuO2ZPn9Kpg+xpbm9XtP7ZLw3Ep2BCmSqtnll/OdxAqLb4DTN4/wWdrjnFC+L/oQEECu646\",\"remember_me_id\":\"remember_me_id0123456789\",\"parent_remember_me_id\":\"parent_remember_me_id0123456789\",\"receipt_id\":\"receipt_id_123\", \"sharing_outcome\":\"SUCCESS\", \"timestamp\":\"2016-01-01T00:00:00Z\"}}"); var engine = new YotiClientEngine(new HttpClient(handlerMock.Object)); ActivityDetails _ = engine.GetActivityDetailsAsync(EncryptedToken, SdkId, _keyPair, new Uri(Constants.Api.DefaultYotiApiUrl)).Result; Assert.IsTrue(_httpRequestMessage.Headers.Contains(Constants.Api.AuthKeyHeader)); }
public ActivityDetails GetActivityDetails(long userId) { ActivityDetails data = new ActivityDetails(); using (IPDEntities ctx = new IPDEntities()) { data.PersonalDetailsDate = ctx.EmployeePersonalDetails.Where(a => a.UserID == userId).OrderByDescending(m => m.UpdatedDate).Select(a => a.UpdatedDate).FirstOrDefault(); data.ContactDetailsDate = ctx.EmployeeContactDetails.Where(a => a.UserID == userId).OrderByDescending(m => m.UpdatedDate).Select(a => a.UpdatedDate).FirstOrDefault(); data.EducationDetailsDate = ctx.EmployeeEducationDetails.Where(a => a.UserID == userId).OrderByDescending(m => m.UpdatedDate).Select(a => a.UpdatedDate).FirstOrDefault(); data.EmploymentDetailsDate = ctx.EmploymentDetails.Where(a => a.UserID == userId).OrderByDescending(m => m.UpdatedDate).Select(a => a.UpdatedDate).FirstOrDefault(); data.FamilyDetailsDate = ctx.EmployeeFamilyDetails.Where(a => a.UserID == userId).OrderByDescending(m => m.UpdatedDate).Select(a => a.UpdatedDate).FirstOrDefault(); data.UploadDocumentDetailsDate = ctx.DocumentDetails.Where(a => a.UserID == userId).OrderByDescending(m => m.UpdatedDate).Select(a => a.UpdatedDate).FirstOrDefault(); } return(data); }
public async void SaveActivity() { var activity_data = new ActivityDetails() { activity_guid = null, start_date = DateTime.Now, end_date = DateTime.Now, description = "only_for_test" }; var current_org = "feb1c383e29744f09dbb016ab1342d09"; _saveActivityGuid = await _activityService.SaveActivity(current_org, activity_data); Assert.NotNull(_saveActivityGuid); }
public void EmptyStringParentRememberMeIdShouldBeHandled() { const string wrappedReceiptKey = "kyHPjq2+Y48cx+9yS/XzmW09jVUylSdhbP+3Q9Tc9p6bCEnyfa8vj38AIu744RzzE+Dc4qkSF21VfzQKtJVILfOXu5xRc7MYa5k3zWhjiesg/gsrv7J4wDyyBpHIJB8TWXnubYMbSYQJjlsfwyxE9kGe0YI08pRo2Tiht0bfR5Z/YrhAk4UBvjp84D+oyug/1mtGhKphA4vgPhQ9/y2wcInYxju7Q6yzOsXGaRUXR38Tn2YmY9OBgjxiTnhoYJFP1X9YJkHeWMW0vxF1RHxgIVrpf7oRzdY1nq28qzRg5+wC7cjRpS2i/CKUAo0oVG4pbpXsaFhaTewStVC7UFtA77JHb3EnF4HcSWMnK5FM7GGkL9MMXQenh11NZHKPWXpux0nLZ6/vwffXZfsiyTIcFL/NajGN8C/hnNBljoQ+B3fzWbjcq5ueUOPwARZ1y38W83UwMynzkud/iEdHLaZIu4qUCRkfSxJg7Dc+O9/BdiffkOn2GyFmNjVeq754DCUypxzMkjYxokedN84nK13OU4afVyC7t5DDxAK/MqAc69NCBRLqMi5f8BMeOZfMcSWPGC9a2Qu8VgG125TuZT4+wIykUhGyj3Bb2/fdPsxwuKFR+E0uqs0ZKvcv1tkNRRtKYBqTacgGK9Yoehg12cyLrITLdjU1fmIDn4/vrhztN5w="; const string parentRememberMeId = ""; Mock <HttpMessageHandler> handlerMock = SetupMockMessageHandler( HttpStatusCode.OK, "{\"receipt\":{\"wrapped_receipt_key\": \"" + wrappedReceiptKey + "\",\"parent_remember_me_id\":\"" + parentRememberMeId + "\", \"sharing_outcome\":\"SUCCESS\", \"timestamp\":\"2016-01-01T00:00:00Z\"}}"); var engine = new YotiClientEngine(new HttpClient(handlerMock.Object)); ActivityDetails activityDetails = engine.GetActivityDetailsAsync(EncryptedToken, SdkId, _keyPair, new Uri(Constants.Api.DefaultYotiApiUrl)).Result; Assert.AreEqual(string.Empty, activityDetails.ParentRememberMeId); }
/// <summary> /// ListByLoginWithFilter /// Calls [usp_list_Activity_by_Login_with_filter] /// </summary> public override List <ActivityDetails> ListByLoginWithFilter(System.Int32?loginId, System.Int32?pageIndex, System.Int32?pageSize, System.String tableSearch, System.String contactSearch, System.String cmSearch, System.String employeeSearch) { SqlConnection cn = null; SqlCommand cmd = null; try { cn = new SqlConnection(this.ConnectionString); cmd = new SqlCommand("usp_list_Activity_by_Login_with_filter", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 30; cmd.Parameters.Add("@LoginId", SqlDbType.Int).Value = loginId; cmd.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex; cmd.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize; cmd.Parameters.Add("@TableSearch", SqlDbType.NVarChar).Value = tableSearch; cmd.Parameters.Add("@ContactSearch", SqlDbType.NVarChar).Value = contactSearch; cmd.Parameters.Add("@CMSearch", SqlDbType.NVarChar).Value = cmSearch; cmd.Parameters.Add("@EmployeeSearch", SqlDbType.NVarChar).Value = employeeSearch; cn.Open(); DbDataReader reader = ExecuteReader(cmd); List <ActivityDetails> lst = new List <ActivityDetails>(); while (reader.Read()) { ActivityDetails obj = new ActivityDetails(); obj.TableName = GetReaderValue_String(reader, "TableName", ""); obj.RowId = GetReaderValue_Int32(reader, "RowId", 0); obj.RowNumber = GetReaderValue_Int32(reader, "RowNumber", 0); obj.CompanyNo = GetReaderValue_Int32(reader, "CompanyNo", 0); obj.CompanyName = GetReaderValue_String(reader, "CompanyName", ""); obj.CurrencyCode = GetReaderValue_String(reader, "CurrencyCode", ""); obj.PartName = GetReaderValue_String(reader, "PartName", ""); obj.RowValue = GetReaderValue_NullableDouble(reader, "RowValue", null); obj.RowDate = GetReaderValue_DateTime(reader, "RowDate", DateTime.MinValue); obj.ContactName = GetReaderValue_String(reader, "ContactName", ""); obj.RowCnt = GetReaderValue_NullableInt32(reader, "RowCnt", null); lst.Add(obj); obj = null; } return(lst); } catch (SqlException sqlex) { //LogException(sqlex); throw new Exception("Failed to get Activitys", sqlex); } finally { cmd.Dispose(); cn.Close(); cn.Dispose(); } }
public bool Equals(DestinyHistoricalStatsPeriodGroup input) { if (input == null) { return(false); } return (( Period == input.Period || (Period != null && Period.Equals(input.Period)) ) && ( ActivityDetails == input.ActivityDetails || (ActivityDetails != null && ActivityDetails.Equals(input.ActivityDetails)) ) && ( Values == input.Values || (Values != null && Values.SequenceEqual(input.Values)) )); }
public void Update(DestinyHistoricalStatsPeriodGroup?other) { if (other is null) { return; } if (Period != other.Period) { Period = other.Period; OnPropertyChanged(nameof(Period)); } if (!ActivityDetails.DeepEquals(other.ActivityDetails)) { ActivityDetails.Update(other.ActivityDetails); OnPropertyChanged(nameof(ActivityDetails)); } if (!Values.DeepEqualsDictionary(other.Values)) { Values = other.Values; OnPropertyChanged(nameof(Values)); } }
public void YotiClientEngine_TokenDecodedSuccessfully() { var keyPair = GetKeyPair(); string sdkId = "fake-sdk-id"; FakeHttpRequester httpRequester = new FakeHttpRequester((httpClient, httpMethod, uri, headers, byteContent) => { Assert.AreEqual("/api/v1/profile/" + _token, uri.AbsolutePath); return(Task.FromResult(new Response { Success = false, StatusCode = 500 })); }); YotiClientEngine engine = new YotiClientEngine(httpRequester); ActivityDetails activityDetails = engine.GetActivityDetails(_encryptedToken, sdkId, keyPair, YotiConstants.DefaultYotiApiUrl); Assert.IsNotNull(activityDetails.Outcome); }
private static Activity PopulateFromDBDetailsObject(ActivityDetails obj) { Activity objNew = new Activity(); objNew.ActivityId = obj.ActivityId; objNew.TableName = obj.TableName; objNew.KeyNo = obj.KeyNo; objNew.UpdatedBy = obj.UpdatedBy; objNew.DLUP = obj.DLUP; objNew.ClientNo = obj.ClientNo; objNew.RowId = obj.RowId; objNew.RowNumber = obj.RowNumber; objNew.CompanyNo = obj.CompanyNo; objNew.CompanyName = obj.CompanyName; objNew.CurrencyCode = obj.CurrencyCode; objNew.PartName = obj.PartName; objNew.RowValue = obj.RowValue; objNew.RowDate = obj.RowDate; objNew.ContactName = obj.ContactName; objNew.RowCnt = obj.RowCnt; objNew.RowNum = obj.RowNum; return(objNew); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string token = null; IReadableStringCollection query = Request.Query; IList <string> values = query.GetValues("token"); if (values != null && values.Count == 1) { token = values[0]; } string stateCookieKey = Constants.StatePrefix + Options.AuthenticationType; string stateCookie = Request.Cookies[stateCookieKey]; if (string.IsNullOrWhiteSpace(stateCookie)) { _logger.WriteWarning("{0} cookie not found.", stateCookie); return(null); } var cookieOptions = new CookieOptions { HttpOnly = true, Secure = Request.IsSecure }; Response.Cookies.Delete(stateCookieKey, cookieOptions); properties = Options.StateDataFormat.Unprotect(stateCookie); if (properties == null) { return(null); } // Request the token ActivityDetails activityDetails = await _yotiClient.GetActivityDetailsAsync(token); if (activityDetails.Outcome != ActivityOutcome.Success) { // TODO: Check how this is handled throw new HttpRequestException(); } var context = new YotiAuthenticatedContext(Context, activityDetails.UserProfile); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrEmpty(context.User.Id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.User.Id, ClaimValueTypes.String, Options.AuthenticationType)); } if (context.User.Selfie != null) { context.Identity.AddClaim(new Claim("selfie", Convert.ToBase64String(context.User.Selfie.Data), context.User.Selfie.Type.ToString(), Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.User.GivenNames)) { context.Identity.AddClaim(new Claim("given_names", context.User.GivenNames, ClaimValueTypes.String, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.User.FamilyName)) { context.Identity.AddClaim(new Claim("family_name", context.User.FamilyName, ClaimValueTypes.String, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.User.MobileNumber)) { context.Identity.AddClaim(new Claim("phone_number", context.User.MobileNumber, ClaimValueTypes.String, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.User.EmailAddress)) { context.Identity.AddClaim(new Claim("email_address", context.User.EmailAddress, ClaimValueTypes.String, Options.AuthenticationType)); } if (context.User.DateOfBirth != null) { context.Identity.AddClaim(new Claim("date_of_birth", context.User.DateOfBirth.Value.ToString("yyyy-MM-dd"), ClaimValueTypes.String, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.User.Address)) { context.Identity.AddClaim(new Claim("postal_address", context.User.Address, ClaimValueTypes.String, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.User.Gender)) { context.Identity.AddClaim(new Claim("gender", context.User.Gender, ClaimValueTypes.String, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.User.Nationality)) { context.Identity.AddClaim(new Claim("nationality", context.User.Nationality, ClaimValueTypes.String, Options.AuthenticationType)); } foreach (var attributeName in context.User.OtherAttributes.Keys) { var attributeValue = context.User.OtherAttributes[attributeName]; context.Identity.AddClaim(new Claim(attributeName, attributeValue.ToString(), attributeValue.Type.ToString(), Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }
public Result <ActivityDetails, ValidityError> SaveActivity(EditableActivity activity, int ownerId) { try { if (activity is null) { return(ValidityError.ForInvalidObject <ActivityDetails>("no activity provided")); } if (string.IsNullOrWhiteSpace(activity.Name)) { return(ValidityError.ForInvalidObject <ActivityDetails>("empty name")); } TimeSpan?period = null; if (!activity.PeriodUnit.HasValue) { activity.PeriodCount = null; } else if (!activity.PeriodCount.HasValue) { activity.PeriodUnit = null; } else if (activity.PeriodCount.Value == 0) { return(ValidityError.ForInvalidObject <ActivityDetails>("invalid period count")); } else { switch (activity.PeriodUnit.Value) { case Unit.Hour: period = TimeSpan.FromHours(activity.PeriodCount.Value); break; case Unit.Day: period = TimeSpan.FromDays(activity.PeriodCount.Value); break; case Unit.Week: period = TimeSpan.FromDays(7 * activity.PeriodCount.Value); break; case Unit.Month: period = TimeSpan.FromDays(365.25 / 12 * activity.PeriodCount.Value); break; case Unit.Year: period = TimeSpan.FromDays(365.25 * activity.PeriodCount.Value); break; default: return(ValidityError.ForInvalidObject <ActivityDetails>("invalid period unit")); } } activity.Participants ??= new List <UserInfo>(); // sanitize the default notification settings to ensure there's only one per type var defaultNotificationSettings = (activity.DefaultNotificationSettings ?? new List <NotificationInfo>()) .Where(x => x.AnyActive && x.Type.IsAllowed(activity.TakeTurns)) .GroupBy(x => x.Type) .Select(g => g.First()) .ToDictionary(x => x.Type); if (activity.Id < 0) { return(ValidityError.ForInvalidObject <ActivityDetails>("invalid ID")); } var userIds = activity.Participants.Select(p => p.Id).Append(ownerId).ToHashSet(); var add = false; Activity activityToUpdate; if (activity.Id == 0) { add = true; activityToUpdate = new Activity { Participants = _db.Users.Where(user => userIds.Contains(user.Id)).ToList().Select(CreateNewParticipant).ToList(), DefaultNotificationSettings = _mapper.Map <List <DefaultNotificationSetting> >(defaultNotificationSettings.Values), Owner = _db.Users.Find(ownerId), Turns = new List <Turn>(0) }; foreach (var participant in activityToUpdate.Participants) { participant.NotificationSettings.AddRange(_mapper.Map <List <NotificationSetting> >(defaultNotificationSettings.Values)); } } else { activityToUpdate = GetActivity(activity.Id, false, true, true); if (activityToUpdate is null) { return(ValidityError.ForInvalidObject <ActivityDetails>("invalid ID")); } if (activityToUpdate.IsDisabled) { return(ValidityError.ForInvalidObject <ActivityDetails>("activity is disabled")); } // remove any participants that should no longer be there activityToUpdate.Participants.RemoveAll(x => !userIds.Contains(x.UserId)); // remove any existing participants from the list so we're left with only new participants userIds.ExceptWith(activityToUpdate.Participants.Select(x => x.UserId)); // add new participants activityToUpdate.Participants.AddRange(_db.Users.Where(user => userIds.Contains(user.Id)).ToList().Select(CreateNewParticipant)); // remove any default notifications that should no longer be there activityToUpdate.DefaultNotificationSettings.RemoveAll(x => { var remove = !defaultNotificationSettings.ContainsKey(x.Type); if (remove) { foreach (var participant in activityToUpdate.Participants) { participant.NotificationSettings.RemoveAll(y => y.Type == x.Type && y.Origin == NotificationOrigin.Default); } } return(remove); }); // remove any participant notifications that are no longer valid because the activity no longer has turns needed if (activityToUpdate.TakeTurns && !activity.TakeTurns) { foreach (var participant in activityToUpdate.Participants) { participant.NotificationSettings.RemoveAll(x => !x.Type.IsAllowed(activity.TakeTurns)); } } // update any existing default notification and remove it from the new list foreach (var noteToUpdate in activityToUpdate.DefaultNotificationSettings) { if (defaultNotificationSettings.Remove(noteToUpdate.Type, out var updatedNote)) { _mapper.Map(updatedNote, noteToUpdate); // update any existing participant notifications that originated from a default notification foreach (var participantNote in activityToUpdate.Participants.SelectMany(x => x.NotificationSettings).Where(x => x.Type == updatedNote.Type && x.Origin == NotificationOrigin.Default)) { //make sure we don't clear the participant ID updatedNote.ParticipantId = participantNote.ParticipantId; _mapper.Map(updatedNote, participantNote); } } } // add any remaining notifications foreach (var note in defaultNotificationSettings.Values) { activityToUpdate.DefaultNotificationSettings.Add(_mapper.Map <DefaultNotificationSetting>(note)); foreach (var participant in activityToUpdate.Participants.Where(participant => participant.NotificationSettings.All(x => x.Type != note.Type))) { participant.NotificationSettings.Add(_mapper.Map <NotificationSetting>(note)); } } } activityToUpdate.OwnerId = ownerId; activityToUpdate.Name = activity.Name; activityToUpdate.Description = string.IsNullOrWhiteSpace(activity.Description) ? null : activity.Description.Trim(); activityToUpdate.PeriodCount = activity.PeriodCount; activityToUpdate.PeriodUnit = activity.PeriodUnit; activityToUpdate.Period = period; activityToUpdate.TakeTurns = activity.TakeTurns; if (add) { _db.Activities.Add(activityToUpdate); } else { _db.Activities.Update(activityToUpdate); } var details = ActivityDetails.Calculate(activityToUpdate, ownerId, _mapper); _db.SaveChanges(); details.Update(activityToUpdate); return(Result.Success <ActivityDetails, ValidityError>(details)); } catch (Exception e) { var message = $"Failed to save activity '{activity?.Id}'"; _logger.LogError(e, message); return(ValidityError.ForInvalidObject <ActivityDetails>(message)); } Participant CreateNewParticipant(User user) { return(new Participant { UserId = user.Id, User = user, DismissUntilTimeOfDay = _appSettings.Value.PushNotifications.DefaultDismissTime, NotificationSettings = new List <NotificationSetting>() }); } }
public ActivityDetails GetActivityDetailsShallow(int activityId, int userId) { var activity = GetActivity(activityId, true, false); return(activity is null ? null : ActivityDetails.Populate(activity, userId, _mapper)); }
public ActivityDetails GetActivityDetails(int activityId, int userId) { var activity = GetActivity(activityId, true, true); return(activity is null ? null : ActivityDetails.Calculate(activity, userId, _mapper)); }
public async Task <Result <ActivityDetails, TurnError> > TakeTurnAsync(DateTimeOffset activityModifiedDate, int activityId, int byUserId, int forUserId, DateTimeOffset when) { try { var now = DateTimeOffset.Now; _db.Turns.Add(new Turn { ActivityId = activityId, CreatorId = byUserId, UserId = forUserId, Occurred = when }); var activity = GetActivity(activityId, false, true); if (activity == null) { _logger.LogError($"Activity {activityId} is missing"); return(Result.Failure <ActivityDetails, TurnError>(TurnError.ActivityMissing)); } if (_appSettings.Value.ValidateActivityModifiedDate && activity.ModifiedDate != activityModifiedDate) { _logger.LogWarning($"Activity {activity.Id} was modified {activity.ModifiedDate} and doesn't match {activityModifiedDate}"); return(Result.Failure <ActivityDetails, TurnError>(TurnError.ActivityModified)); } var details = ActivityDetails.Calculate(activity, byUserId, _mapper); var turnTaker = await _db.Users.FindAsync(forUserId); FormattableString fs = $"{turnTaker.DisplayName} took a turn."; var myTurnBuilder = new StringBuilder().AppendFormattable(fs); var otherTurnBuilder = new StringBuilder().AppendFormattable(fs); if (details.CurrentTurnUserId.HasValue) { otherTurnBuilder.AppendFormattable($" It's {details.CurrentTurnUserDisplayName}'s turn."); myTurnBuilder.AppendFormattable($" It's your turn."); } if (details.Due.HasValue) { fs = $" Due in {(details.Due.Value - now).ToDisplayString()}."; otherTurnBuilder.AppendFormattable(fs); myTurnBuilder.AppendFormattable(fs); } var myTurnMessage = myTurnBuilder.ToString(); var otherTurnMessage = otherTurnBuilder.ToString(); var url = $"{_appSettings.Value.PushNotifications.ServerUrl}/activity/{activityId}"; var failures = new List <PushFailure>(); foreach (var participant in activity.Participants) { var pushNotified = false; foreach (var setting in participant.NotificationSettings.OrderBy(x => x.Type)) { switch (setting.Type) { case NotificationType.OverdueAnybody: case NotificationType.OverdueMine: setting.NextCheck = now; // send a close push notification in case they still have a previous notification open but not if they // already got a notification about a turn being taken because that will replace any existing notification if (setting.Push && !pushNotified) { failures.AddRange(await _pushNotificationService.SendCloseToAllDevicesAsync("turn", setting.Participant.UserId, activityId.ToString())); pushNotified = true; } break; case NotificationType.TurnTakenAnybody: if (setting.Push) { failures.AddRange(await _pushNotificationService.SendToAllDevicesAsync("turn", setting.Participant.UserId, activity.Name, otherTurnMessage, url, activityId.ToString())); pushNotified = true; } break; case NotificationType.TurnTakenMine: if (details.CurrentTurnUserId.HasValue && setting.Push && setting.Participant.UserId == details.CurrentTurnUserId) { failures.AddRange(await _pushNotificationService.SendToAllDevicesAsync("turn", setting.Participant.UserId, activity.Name, myTurnMessage, url, activityId.ToString())); pushNotified = true; } break; default: _logger.LogError($"Unhandled notification type {setting.Type}"); break; } } } // Ensure we are done sending each push message before cleaning up failures and continuing await _pushNotificationService.CleanupFailuresAsync(failures); // Always mark the activity as modified when taking a turn so our checks elsewhere that compare // the modified timestamp will still work for activities that wouldn't normally have anything update, // like when they're non-periodic or the next-turn user doesn't change. _db.Entry(activity).State = EntityState.Modified; await _db.SaveChangesAsync(); details.Update(activity); return(Result.Success <ActivityDetails, TurnError>(details)); } catch (Exception e) { _logger.LogError(e, "Failed to take a turn"); return(Result.Failure <ActivityDetails, TurnError>(TurnError.Exception)); } }
public bool InsertActivity(Model.ActivityPostModel activityPostModel) { bool result = false; try { List <int> arr = new List <int>(); foreach (var item in activityPostModel.ActivityType.ActivitySubType) { arr.AddRange(item.SubTypeChilds.Select(s => s.ActivitySubTypeChildId).ToList()); } Entity.ActivityDetails activityDetails = new ActivityDetails { ActivityDetailsId = 0, ActivityTypeId = activityPostModel.ActivityType.ActivityTypeId, ActivitySubTypeIds = string.Join("|", activityPostModel.ActivityType.ActivitySubType.Select(s => s.ActivitySubTypeId).ToArray()), ActivitySubTypeChildIds = string.Join("|", arr.ToArray()), ActivityDateTime = activityPostModel.ActivityDate, StaffId = activityPostModel.StaffId, ImageURL = activityPostModel.ImageURL, Notes = activityPostModel.Notes, IsActive = true }; _schoolContext.ActivityDetails.Add(activityDetails); _schoolContext.SaveChanges(); if (activityDetails.ActivityDetailsId > 0) { foreach (var studentId in activityPostModel.StudentIds) { Entity.StudentActivityMapping studentActivityMapping = new StudentActivityMapping { ActivityDetailsId = activityDetails.ActivityDetailsId, IsClassLevel = activityPostModel.IsClassLevel, IsSchoolLevel = activityPostModel.IsSchoolLevel, IsStudentLevel = activityPostModel.IsStudentLevel, StudentId = studentId, ClassId = activityPostModel.ClassId }; _schoolContext.StudentActivityMapping.Add(studentActivityMapping); } var recordsAffect = _schoolContext.SaveChanges(); if (recordsAffect > 0) { result = true; } } return(result); } catch (Exception ex) { return(result); throw; } }
public void TestProfile() { Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair sandboxKeyPair; using (StreamReader stream = File.OpenText("path/to/hub-private-key.pem")) { sandboxKeyPair = Yoti.Auth.CryptoEngine.LoadRsaKey(stream); } const string sandboxClientSdkid = "your SDK ID"; SandboxClient sandboxClient = new SandboxClientBuilder() .WithClientSdkId(sandboxClientSdkid) .WithKeyPair(sandboxKeyPair) .Build(); SandboxAgeVerification ageVerification = new SandboxAgeVerificationBuilder() .WithDateOfBirth(new DateTime(2001, 12, 31)) .WithAgeOver(18) .Build(); DateTime expiryDate = DateTime.UtcNow.AddDays(1); var documentImages = new SandboxDocumentImagesBuilder() .WithJpegContent(Encoding.UTF8.GetBytes("some JPEG content")) .WithPngContent(Encoding.UTF8.GetBytes("some PNG content")) .Build(); SandboxExtraData sandboxExtraData = new SandboxExtraDataBuilder() .WithDataEntry( new SandboxAttributeIssuanceDetailsBuilder() .WithDefinition("attribute.name") .WithExpiryDate(expiryDate) .WithIssuanceToken("some-issuance-token") .Build()) .Build(); YotiTokenRequest tokenRequest = new YotiTokenRequestBuilder() .WithRememberMeId("some Remember Me ID") .WithGivenNames("some given names") .WithFamilyName("some family name") .WithFullName("some full name") .WithDateOfBirth(new DateTime(1980, 10, 30)) .WithAgeVerification(ageVerification) .WithGender("some gender") .WithPhoneNumber("some phone number") .WithNationality("some nationality") .WithStructuredPostalAddress(Newtonsoft.Json.JsonConvert.SerializeObject(new { building_number = 1, address_line1 = "some address" })) .WithBase64Selfie(Convert.ToBase64String(Encoding.UTF8.GetBytes("some base64 encoded selfie"))) .WithEmailAddress("some@email") .WithDocumentDetails("PASSPORT USA 1234abc") .WithDocumentImages(documentImages) .WithExtraData(sandboxExtraData) .Build(); var sandboxOneTimeUseToken = sandboxClient.SetupSharingProfile(tokenRequest); var yotiClient = new YotiClient(new HttpClient(), sandboxClientSdkid, sandboxKeyPair); Uri sandboxUri = new UriBuilder( "https", "api.yoti.com", 443, "sandbox/v1").Uri; yotiClient.OverrideApiUri(sandboxUri); ActivityDetails activityDetails = yotiClient.GetActivityDetails(sandboxOneTimeUseToken); // Perform tests Assert.AreEqual("some@email", activityDetails.Profile.EmailAddress.GetValue()); }