How do I set a target user on JDA - discord

So I'm trying to create a bot to add roles to a targeted user with the command "r.accept insert username here" but I don't know how to get the bot to target the user in question. So where do I place it?
package com.kotadajedi.reina.listeners;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class EventListener extends ListenerAdapter {
public void onMessageReceived(MessageReceivedEvent event) {
String message = event.getMessage().getContentRaw();
if(message.contains("r.accept")) {
event.getGuild().addRoleToMember(event.getMember(), (Role) event.getJDA().getRolesByName("new role", true));
}
}
}

Related

How to grap account's ID or record id(e.g. "0015g00000Bkgg6AAB") on the account record page

I have a custom LWC widget in Account record page, when page loaded my widget, I need to know the account's ID or record id(e.g. "0015g00000Bkgg6AAB"),
my testing code below:
import { LightningElement, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
const fields = [NAME_FIELD, REVENUE_FIELD, BillingAddress_FIELD];
export default class AccountCreator extends LightningElement {
#wire(getRecord, { recordId: '$recordId', fields })
account;
get name() {
return getFieldValue(this.account.data,NAME_FIELD);
}
get revenue() {
return getFieldValue(this.account.data, REVENUE_FIELD);
}
get address() {
return getFieldValue(this.account.data, BillingAddress_FIELD);
}
}
Add these two lines in your class
import { LightningElement, wire, api } from 'lwc'; // 1 - add "api"
export default class AccountCreator extends LightningElement {
#api recordId; // 2 - add variable to magically store the current record's id
}
There are 2 special variables for learning current record's id and current sObject type (if you want to build component that behaves differently when dropped on different pages). Some more info here: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_record_context
Your code looks like you copied from an example, your #wire already listens to changes of the recordId - you just didn't have this variable defined.

Blazor with AzureAD Auth, Context.Identity.User.Name is null

Only authenticated users can access the application as expected. I need to be able to track users via signalr. For example, if I run a ChatHub type of service, I'd like people to be able to chat using their AzureAD username which should be set automatically and not let people set their own usernames.
The hub always shows Context.Identity.User.Name is null.
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.AddTransient<HubConnectionBuilder>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub<App>(selector: "app");
endpoints.MapFallbackToPage("/_Host");
endpoints.MapHub<SomeHub>("/SomeHub");
});
Any idea if here is a way to preserve identity information and pass to SignalR?
Inspect your JWT token and check its claims. You can past it on http://jwt.ms/ to decode it. Then, look for the claims that are being returned that references the user name (in my case it is preferred_username).
Then you can change the default mapping of the Identity.Name using this code:
services.Configure<OpenIdConnectOptions>(AzureADDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters.NameClaimType = "<claim_name_that_returns_username>";
});
My workaround at the moment will be to just pass the username when the connection is created to the hub.
In codebehind (SomePage.razor.cs)
public class SomePageBase : ComponentBase
{
[Inject]
private HubConnectionBuilder _hubConnectionBuilder { get; set; }
[Inject]
private AuthenticationStateProvider authProvider { get; set; }
protected async override Task OnInitializedAsync()
{
var user = (await authProvider.GetAuthenticationStateAsync()).User.Identity.Name;
// in Component Initialization code
var connection = _hubConnectionBuilder // the injected one from above.
.WithUrl("https://localhost:44331/SomeHub")
.Build(); // Build the HubConnection
await connection.StartAsync();
var stringResult =
await connection.InvokeAsync<string>("HubMethodName", user);
}
}

retrieving username with signInWithEmailAndPassword

i manage my users with the Firebase Admin SDK.
On signup i send email,password and username to my endpoint.
i createUserWithEmailAndPassword and create a doc in my firestore
This way i can check if a document already exists and return an error that the username/handle is already taken.
Firestore
- users
- handle
* email
* userId (from createUserWithAndPassword Response)
* createdAt
After the user signInWithEmailandPassword i only have the token, email and userId.. but i need the handle to get the right user details.
what i get from the docs is that there is a default displayName property but i dont know how to set it on signup.
or should i create a custom Token and store the handle inside of it..
im not sure how to go from here
thanks for your help
This is a simple method for what you want:
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
// Sign in success
FirebaseUser user = mAuth.getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(mName).build();
user.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated.");
}
}
});
}
});
Then, to retrieve it, use this wherever required:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address etc
String name = user.getDisplayName();
String email = user.getEmail();
}
There are multiple ways, but I recommend to use this one :)

How can I group Test steps in Allure report

I am looking for solution where I can group test steps in allure report.
Currently what is happening :
For example I have one test case login where there are 5 steps i.e go to login page, enter login detail, click on submit etc. But in allure report I want to show only 1 steps for all 5 login actions. is it possible?
So basically I want to display test case as steps and not scenarios as steps in report.
I searched a lot but did not find a way to do this with allure.
You can call the functions inside allure.step block
#pytest.mark.sanity
class TestExample:
def test_example(self):
with allure.step('Do Login'):
self.go_to_login_page()
self.insert_user_name()
self.insert_password()
def go_to_login_page(self):
Report.report_step('go to login page')
def insert_user_name(self):
Report.report_step('insert username')
def insert_password(self):
Report.report_step('insert password')
Or with page object
#pytest.mark.sanity
class TestExampleTest:
def test_example(self):
with allure.step('Do Login'):
(LoginPage()
.go_to_login_page()
.insert_user_name()
.insert_password())
class LoginPage:
def go_to_login_page(self):
Report.report_step('go to login page')
return self
def insert_user_name(self):
Report.report_step('insert username')
return self
def insert_password(self):
Report.report_step('insert password')
return self
report_step is a static function in Report.py file
def report_step(step_title):
with allure.step(step_title):
pass
The steps will be grouped inside 'Do Login' step
Edit Same idea with Java
public class Test {
public void testMethod() {
doLogin();
}
#Step("Do Login")
public void doLogin() {
new LoginPage()
.goToLoginPage()
.insertUserName("NAME")
.insertPassword("PASSWORD");
}
}
public class LoginPage {
#Step("Go to login page")
public LoginPage goToLoginPage() {
step("goToLoginPage");
return this;
}
#Step("Insert user name {userName}")
public LoginPage insertUserName(String userName) {
return this;
}
#Step("Insert password {password}")
public LoginPage insertPassword(String password) {
return this;
}
}

Grails isn't responding with a 401 during ajax request and timed out session

I'm using grails along with spring security and angularjs. When a user session has expired and the user clicks an ajax action on the page, rather than respond with a 401, the application attempts to redirect to the login page which no response from the original ajax action.
I'm still using a traditional login page and some my application still has some traditional page links, so when a session has expired and a user clicks a page link, I would like to redirect to the login page.
If a user clicks on an ajax request, I would like to get a 401 response rather than the redirected html response so that I can do a redirect in my javascript.
I have the following config setting.
grails.plugin.springsecurity.providerNames = ['hriLoginClientAuthenticationProvider']
grails.plugin.springsecurity.useSecurityEventListener = true
grails.plugin.springsecurity.failureHandler.defaultFailureUrl = '/login?error=1'
grails.plugin.springsecurity.auth.loginFormUrl = '/login'
grails.plugin.springsecurity.logout.postOnly = false
What do I need to do to get ajax request to not redirect to the login page?
I've run into a similar issue and have implemented a filter in the filter chain to detect AJAX requests and respond with a customized HTTP status (you can change it to 401 if you like).
Basically there are three parts to this. The first, is the filter. It's a servlet filter and examines the request as well as the state of the authentication in the session. Second, defining the filter as a bean within the application context in Resources.groovy. Finally, inserting it into the Spring Security filter chain, which I've done in Bootstrap.groovy.
I'll walk you through this now.
First the servlet filter (under src/java)
package com.xyz.security;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.security.web.util.ThrowableCauseExtractor;
import org.springframework.web.filter.GenericFilterBean;
public class AjaxTimeoutRedirectFilter extends GenericFilterBean {
// private static final Logger logger =
// LoggerFactory.getLogger(AjaxTimeoutRedirectFilter.class);
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private int customSessionExpiredErrorCode = 901;
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
// logger.debug("Chain processed normally");
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
RuntimeException ase = (AuthenticationException) throwableAnalyzer
.getFirstThrowableOfType(AuthenticationException.class,
causeChain);
if (ase == null) {
ase = (AccessDeniedException) throwableAnalyzer
.getFirstThrowableOfType(AccessDeniedException.class,
causeChain);
}
if (ase != null) {
if (ase instanceof AuthenticationException) {
throw ase;
} else if (ase instanceof AccessDeniedException) {
if (authenticationTrustResolver
.isAnonymous(SecurityContextHolder.getContext()
.getAuthentication())) {
// logger.info("User session expired or not logged in yet");
String ajaxHeader = ((HttpServletRequest) request)
.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(ajaxHeader)) {
// logger.info("Ajax call detected, send {} error code",
// this.customSessionExpiredErrorCode);
HttpServletResponse resp = (HttpServletResponse) response;
resp.sendError(this.customSessionExpiredErrorCode);
} else {
// logger.info("Redirect to login page");
throw ase;
}
} else {
throw ase;
}
}
}
}
}
private static final class DefaultThrowableAnalyzer extends
ThrowableAnalyzer {
/**
* #see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
*/
protected void initExtractorMap() {
super.initExtractorMap();
registerExtractor(ServletException.class,
new ThrowableCauseExtractor() {
public Throwable extractCause(Throwable throwable) {
ThrowableAnalyzer.verifyThrowableHierarchy(
throwable, ServletException.class);
return ((ServletException) throwable)
.getRootCause();
}
});
}
}
public void setCustomSessionExpiredErrorCode(
int customSessionExpiredErrorCode) {
this.customSessionExpiredErrorCode = customSessionExpiredErrorCode;
}
}
Second, defining the filter as a bean in the application context in Resources.groovy
beans = {
ajaxTimeoutRedirectFilter(com.xyz.security.AjaxTimeoutRedirectFilter)
}
And finally, getting the filter into the Spring Security filter chain (I used BootStrap.groovy for this)
import grails.plugin.springsecurity.SecurityFilterPosition
import grails.plugin.springsecurity.SpringSecurityUtils
class BootStrap {
def init = { servletContext ->
SpringSecurityUtils.clientRegisterFilter('ajaxTimeoutRedirectFilter', SecurityFilterPosition.EXCEPTION_TRANSLATION_FILTER.order + 10)
}
def destroy = {
}
}
Did you consider "locking a screen" when the user is idle on a client-side? Of course you should handle end of a session on server-side but in fact it seems even cleaner and more secure solution than waiting for an action from client side (especially if user has left and left on a screen some sensitive data).
Check out this ng-idle directive.

Resources