How to make it so a certain role is required in order to execute a command - discord.net

I would like require a certain role on the user in order for them to use/execute specific commands.
Is there an easy way to do this for individual commands?

This is using Discord.Net 1.0
var User = Context.User as SocketGuildUser;
var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == "ROLENAME");
if (User.Roles.Contains(role))
{
// do stuff
}

Related

UserID from AuthenticationStateProvider appears empty

I am using AspNetCore Identity and trying to get the UserID of the currently logged in user using AuthenticationStateProvider. I am logging to the console the output however, the username outputs fine but the ID appears empty. The ID field is not empty in the db table. When printing all the claims the subs field seems to be the correct ID. Am I incorrectly retrieving the ID? The approach to retrieve the ID was suggested from another post I found; code is shown below. How might I retrieve the sub value which is the userID, in my page using AuthenticationStateProvider? Thanks in advance.
Retrieving UserID
var user = (await ASP.GetAuthenticationStateAsync()).User;
var UserStringId = user.FindFirst(c => c.Type.Equals(user.Identity.Name))?.Value;
Browser console output
USER ID: blazor.webassembly.js:1
NAME: user4#gmail.com
Sub is correct ID when looping through Claims
var user = (await ASP.GetAuthenticationStateAsync()).User;
var item = user.Claims;
foreach(var x in item)
{
Console.WriteLine(x);
}
Browser console output
s_hash: EQ_bVJS8n32qtUam0wZ1MA
sid: 2E6B597CC9644CFEFDD627532B761F02
sub: 5685a830-cb82-4b60-b459-c0852cc74563 // trying to retrieve this ID
//...
preferred_username: user4#gmail.com
name: user4#gmail.com
Try:
user.FindFirst(c => c.Type == "sub")?.Value

How to manually hash a password using Asp.Net Core 2.2 / IdentityServer4 / SP.NET Core Identity

I am migrating tens of thousands of users from an old website that didn't have a password in the database to this new web application, however, when I try to import the users using the async method, it ends up taking several days to the point where I just ended up cancelling it after a few days.
Now I have resorted to just creating new users directly from _context.Users.Add and assigning their roles, which i can do without a problem.. However, I can't seem to figure out how to create a generic password (all the same password) as these users will just be given a password to view a livestream (doesn't need to be super secure), but I still need the security part for the admin accounts that handle other stuff through the client/admin side UI. If a user signs in, I will have it automatically enter the default password for them.
For some reason though, I cannot get the password hasher to work correctly, as when I sign in, it says that the password is wrong...
This is what I'm using to generate the password and create the users...
var appUser = new ApplicationUser() {
Id = GenerateId(),
AccessFailedCount = 0,
Email = user[1],
PasswordHash = "",
FullName = "Standard User",
UserName = user[1],
PhoneNumber = user[8],
FirstName = user[2],
LastName = user[3],
JoinMailingList = user[4],
Country = user[5],
City = user[6],
StateRegion = user[7]
};
_context.Users.Add(appUser);
var options = new PasswordHasherOptions();
options.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2;
var hasher = new PasswordHasher < ApplicationUser > ();
appUser.PasswordHash = hasher.HashPassword(appUser, "Default8!");
var role = _context.Roles.FirstOrDefault(r => r.Name == "user");
if (role != null) {
var userRole = new IdentityUserRole < string > ();
userRole.RoleId = role.Id;
userRole.UserId = appUser.Id;
_context.UserRoles.Add(userRole);
}
}
_context.SaveChanges();
Can anyone help me out with how I'm supposed to Hash a password to store into the database?
If a user signs in, I will have it automatically enter the default password for them.
If you are using .net core Identity, you can use UserManager.CreateAsync to create the specified user in the backing store with given password:
public virtual System.Threading.Tasks.Task<Microsoft.AspNetCore.Identity.IdentityResult> CreateAsync (TUser user, string password);
Code below is for your reference:
var user = new ApplicationUser { UserName = "wx2#hotmail.com", Email = "wx2#hotmail.com" };
var result = await _userManager.CreateAsync(user, "YourPassWord");
if (result.Succeeded)
{
}
The Identity system will help create the password hash and store in the database . If you still need to manually hash the password , see IPasswordHasher interface .
Edit:
If you want to directly insert/update via database context, you should set correct NormalizedUserName and SecurityStamp to make the system work:
ApplicationUser applicationUser = new ApplicationUser();
Guid guid = Guid.NewGuid();
applicationUser.Id = guid.ToString();
applicationUser.UserName = "wx#hotmail.com";
applicationUser.Email = "wx#hotmail.com";
applicationUser.NormalizedUserName = "wx#hotmail.com";
_context.Users.Add(applicationUser);
var hasedPassword = _passwordHasher.HashPassword(applicationUser, "YourPassword");
applicationUser.SecurityStamp = Guid.NewGuid().ToString();
applicationUser.PasswordHash = hasedPassword;
_context.SaveChanges();
As an addition, if you just want to Update the Password field of an given User:
var oldUser = await _userManager.GetUserAsync(User);
var result = await _userManager.ChangePasswordAsync(oldUser,
updateUserVm.CurrentPassword,
updateUserVm.NewPassword);
And an example to the Question "How I'm supposed to Hash a password?". You could Hash a registered Users Password with the UserManager-Referenced PasswordHasher like this:
ApplicationUser user = _userManager.Users...;
user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, newPassword);
I write my class PasswordHasher based on .net6 PasswordHasher docs latest version (V3) in this stackoverflow answer :
https://stackoverflow.com/a/72429730/9875486

How to check if user is part of an AD group? (even group within a group)

I need to check if users logging into the console application I am making are part of a DL (let's call it DL-A).
Some users aren't directly part of DL-A, but of other DLs that are a member of DL-A. The code that I have working only checks the groups of which the user is directly a member of. How do I check this?
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "DL-A");
if (user != null)
{
if (user.IsMemberOf(group))
{
...
}
}
One way you can see if the user is a member of a nested group is get all the users from a group recursively. I am using user and group from your code:
....
if (group != null)
{
var users = group.GetMembers(true); //this will get nested users
var contains = users.Contains(user);
if (contains)
{
//user found
}
}
...

PDO INSERT & UPDATE query to different tables

I have a PDO SQL script which enables a user to complete a form which captures band information. It then posts this information to my database table called 'bands'. This works fine.
Simultaneously, I would like the script to update a different table called 'users' which has a column called 'num_bands' which needs to increase by a value of +1 if the user creates more than one band.
I have tried a number of methods, but none of them work. The script seems to be able to INSERT to the 'bands' table perfectly, but I cannot UPDATE the 'users' table. Here is the 'register_band' script:
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: ../index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to ../index.php");
}
// This if statement checks to determine whether the registration form has been submitted
// If it has, then the registration code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['username']))
{
// Note that die() is generally a terrible way of handling user errors
// like this. It is much better to display the error with the form
// and allow the user to correct their mistake. However, that is an
// exercise for you to implement yourself.
die("Please enter a username.");
}
// An INSERT query is used to add new rows to a database table.
// Again, we are using special tokens (technically called parameters) to
// protect against SQL injection attacks.
$query = "
INSERT INTO bands (
member_id,
username,
bandname,
bandhometown,
bandtype
) VALUES (
:member_id,
:username,
:bandname,
:bandhometown,
:bandtype
)
";
// Here we prepare our tokens for insertion into the SQL query. We do not
// store the original password; only the hashed version of it. We do store
// the salt (in its plaintext form; this is not a security risk).
$query_params = array(
':member_id' => $_POST['member_id'],
':username' => $_POST['username'],
':bandname' => $_POST['bandname'],
':bandhometown' => $_POST['bandhometown'],
':bandtype' => $_POST['bandtype']
);
try
{
// Execute the query to create the user
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$query2 = "UPDATE users
SET num_bands = num_bands + 1
WHERE id = :member_id";
$stmt2 = $db->prepare($query2);
// This redirects the user to the private page after they register
header("Location: ../gig_view.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to ../gig_view.php");
}
?>
I'm running this in non-production mode at the moment, so the code is not 100%. How do I get the script to UPDATE the 'users' table?
$stmt->closeCursor();
$query2 = "UPDATE users
SET num_bands = num_bands + 1
WHERE id = :member_id";
$stmt2 = $db->prepare($query2);
$params = array(':member_id' => $_POST['member_id']);
$result = $stmt2->execute($params);
The code you have here is well documented, and explains how to use PDO statements, prepared queries and how to execute them with parameters.
Just follow the same pattern as you did with your SELECT, only the string of the query is meant to change here.

Checking for Linq Variables

i m making wcf service for login. my code for accesssing db data using linq is :
var result = from detail in dc.tbl_User_Masters where detail.User_Type_Id == 2
select new UserVerification
{
Uname = detail.User_Login_Name,
Password = detail.User_Pwd
};
where UserVerification is class which has Uname and Password properties stored..now how to check that variable that if they are null then we'll not allow login...i dont know how to do that with linq..
You probably need to filter on the user/password you're trying to authenticate:
var givenUname = "robertpaulson";
var givenPassword = "bob";
var result = (
from detail in dc.tbl_User_Masters
where detail.User_Type_Id == 2
where detail.User_Login_Name == givenUname && detail.User_Pwd == givenPassword
select detail
).SingleOrDefault();
Now result will either be null or have the details for the authenticated user.
You don't have to do that in Linq. You have completed your linq part.
You may use
if (result == null) {//code for stoping the login process}
or
if (result.UserName == null) {//code for stoping the login process}