I have Xamarin forms app ,the user will register and login for first time and save username in SQLite database ,then I want the app check if the database found and the username is have been inserted any time he open the app.
i used this code in registration page :
SqliteUser squser = new SqliteUser()
{
appUser = user
};
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
conn.CreateTable<SqliteUser>();
int rows = conn.Insert(squser);
};
I checked the user is inserted successfully.
Now I made CheckUserpage to check if there is a user registered, if yes the alert me the name of first user inserted :-
public partial class CheckUserPage : ContentPage
{
public CheckUserPage()
{
InitializeComponent();
CheckSqlUser();
}
private void CheckSqlUser() {
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
var userQuery = conn.Table<SqliteUser>().Where(a=>a.appUser!="");
if (userQuery != null) {
DisplayAlert("user found", "user found", "OK");
}
};
}
}
How can I get the first user name inserted ?
Best Regard
to get the first value in a list, use LINQ
using System.Linq;
var userQuery = conn.Table<SqliteUser>().Where(a=>a.appUser!="");
var results = userQuery.ToList();
var first = results.FirstOrDefault();
Related
I have implemented an extension grant in my Identity Server instance. The purpose of this is for a mobile app to switch contexts between an authenticated user and a public kiosk type device.
When the user enters this mode, I acquire a new token and include the proper grant type.
I used the IS documentation as a base. Nothing crazy going on here at all, I just add some additional claims to this token to be able to access things in the API the user may otherwise not be set up for.
public class KioskGrantValidator : IExtensionGrantValidator
{
private readonly ITokenValidator _validator;
public KioskGrantValidator(ITokenValidator validator)
{
_validator = validator;
}
public string GrantType => "kiosk";
public async Task ValidateAsync(ExtensionGrantValidationContext context)
{
var userToken = context.Request.Raw.Get("token");
if (string.IsNullOrEmpty(userToken))
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
return;
}
var result = await _validator.ValidateAccessTokenAsync(userToken);
if (result.IsError)
{
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant);
return;
}
// get user's identity
var sub = result.Claims.FirstOrDefault(c => c.Type == "sub").Value;
// I add some custom claims here
List<Claim> newClaims = new()
{
new Claim(ClaimTypes.Name, "kiosk")
}
context.Result = new GrantValidationResult(sub, GrantType, claims: newClaims);
return;
}
}
Now, the question is refreshing this token.
For this grant to work I'm passing in the access token, which expires, eventually causing the ValidateAccessTokenAsync to fail.
Wanted to see what the best way to refresh this token is? Currently the best way I have found is to refresh the original user access token when this one is about to expire, then get a second token with the new grant. This works, but seems maybe unnecessary.
Thanks for any input!
I'm using Abp vNext v3.3 and want to use Abp Text Template to overwrite existing Forget (Reset) password template, however I don't know what's the existing .tpl it uses for resetting password, I need the reset password "link" tag name within the template.
Override the following method in your custom class, so that you can get the link and if you want you can execute the base method to continue the routine steps.
https://github.com/abpframework/abp/blob/dev/modules/account/src/Volo.Abp.Account.Application/Volo/Abp/Account/Emailing/AccountEmailer.cs#L40
Note, I didn't test the code, just wrote out of my mind
[Dependency(ReplaceServices = true)]
[ExposeServices(typeof(AccountEmailer ))]
public class MyAccountEmailer: AccountEmailer {
public virtual async Task SendPasswordResetLinkAsync(
IdentityUser user,
string resetToken,
string appName,
string returnUrl = null,
string returnUrlHash = null) {
/* THIS IS THE LINK. DO WHATEVER YOU WANT! */
var link = CreateLink(user, resetToken, appName, returnUrl, returnUrlHash);
await base.SendPasswordResetLinkAsync();
}
private string CreateLink(IdentityUser user,
string resetToken,
string appName,
string returnUrl = null,
string returnUrlHash = null
)
{
var url = await AppUrlProvider.GetResetPasswordUrlAsync(appName);
var link = $ "{url}?userId={user.Id}&tenantId={user.TenantId}&resetToken={UrlEncoder.Default.Encode(resetToken)}";
if (!returnUrl.IsNullOrEmpty()) {
link += "&returnUrl=" + NormalizeReturnUrl(returnUrl);
}
if (!returnUrlHash.IsNullOrEmpty()) {
link += "&returnUrlHash=" + returnUrlHash;
}
}
}
}
I am trying to add the creation of roles while I create a new Tenant from the UI on ABP.IO Framework version 4.
From ABP.IO documentation, I found that by using the existing class SaasDataSeedContributor I can "seed" some datas while I am creating a new Tenant.
My issue is that from this class, I do not have permission to use IIdentityRoleAppService.CreateAsync method (Given policy has not granted).
So I tried to go through an AppService and use IdentityRoleManager or even IIdentityRoleRepository,but it is not possible to create IdentityRole object as the constructor is inaccessible due to his protection level.
Any thought about it? Is there any another way to do action while creating a tenant appart using SaasDataSeedContributor. Or maybe I am doing something wrong here.
Thanks for your help
Try this.
public class AppRolesDataSeedContributor : IDataSeedContributor, ITransientDependency
{
private readonly IGuidGenerator _guidGenerator;
private readonly IdentityRoleManager _identityRoleManager;
public AppRolesDataSeedContributor(IGuidGenerator guidGenerator, IdentityRoleManager identityRoleManager)
{
_guidGenerator = guidGenerator;
_identityRoleManager = identityRoleManager;
}
public async Task SeedAsync(DataSeedContext context)
{
if (context.TenantId.HasValue)
{
// try this for a single known role
var role = await _identityRoleManager.FindByNameAsync("new_role");
if (role == null)
{
var identityResult = await _identityRoleManager.CreateAsync(
new IdentityRole(_guidGenerator.Create(), "new_role", context.TenantId.Value));
}
// or this (not tested) for multiple roles
/*
var newRoles = new[] { "role1", "role2" };
var identityRoles = from r
in _identityRoleManager.Roles
where r.TenantId == context.TenantId.Value
select r.Name;
var except = newRoles.Except(identityRoles.ToList());
foreach (var name in except)
{
var identityResult = await _identityRoleManager.CreateAsync(
new IdentityRole(_guidGenerator.Create(), name, context.TenantId.Value));
}
*/
}
}
}
im trying to create mvc application with role based authorization. Currently i want 2 roles only, admin and user. I already make simple authorization work, but still without role. I already search so many reference in internet but still cant find one that works with me. Please help, thank you.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
string loginquery = "select UserId,Password,Roles from UserAcc where "
+ "userId = #p0 and Password = #p1";
var a= db.User.SqlQuery(loginquery,model.userid, model.password).Count() ;
if (a>0)
{
FormsAuthentication.SetAuthCookie(model.userid, false);
Session["userid"] = model.userid.ToString();
return RedirectToAction("Index", "Employee");
}
else { return RedirectToAction("Login"); }
}
else
{
ModelState.AddModelError("", "EmailId or Password Incorrect.");
}
return View(model);
}
I want the program to set role authorization based on role field in database
SELECT TOP 1000 [UserId]
,[Password]
,[Roles] FROM [ESS].[dbo].[UserAcc]
And i want to filter my controller like this
namespace TEST2.Controllers{[Authorize(Roles = "user")]
public class EmployeeController : Controller
{
Thankyou,
Right now I'm working with silverlight project and I'm stuck on how to list all of users and user profile together.
Now I'm using this method to get all user via WCF
public IEnumerable<MembershipServiceUser> GetAllUsers()
{
return Membership.GetAllUsers().Cast<MembershipUser>().Select(u => new MembershipServiceUser(u));
}
public void FromMembershipUser(MembershipUser user)
{
this.Comment = user.Comment;
this.CreationDate = user.CreationDate;
this.Email = user.Email;
this.IsApproved = user.IsApproved;
this.UserName = user.UserName;
}
I can get all user from those code above but I don't know how extactly to get user profile
eg. Firstname , Lastname , etc..
You can create a new instance of ProfileBase and access the profile fields with the method GetPropertyValue("propertyName"), where propertyName is the name of your custom registration data.
var profile = ProfileBase.Create(user.UserName);
this.CustomProperty = profile.GetPropertyValue("customPropertyName");
I'm not 100% sure about the syntax, I come from a vb environment and haven't written any c# in a while.
ProfileInfoCollection profiles = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All);
foreach (ProfileInfo pi in profiles)
{
ProfileCommon p = Profile.GetProfile(pi.UserName);
countries.Add(p.Country);
}