How we can add prisma middleware in different file? - middleware

I have multiple middleware for a single route. can i breakdown code and move middleware in different file?.I tried with import a middleware in server file but it is not working

try to add like these
import bcrypt from 'bcryptjs'
import { PrismaClient, Prisma } from '#prisma/client'
const prisma: PrismaClient = new PrismaClient()
prisma.$use(async (params: Prisma.MiddlewareParams, next) => {
if (params.action == 'create' && params.model == 'User') {
let user = params.args.data
let salt = bcrypt.genSaltSync(10)
let hash = bcrypt.hashSync(user.password, salt)
user.password = hash
}
return await next(params)
})

Related

Postman GET request to Binance API

I'm trying to send a GET request to Binance's API, but I don't exactly know how to.
Here is the documentation page: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data
I have a private apiKey and secretKey.
I can do a general request to Binance, but I cannot get my private data, using my private keys.
First try:
For the GET request in Postman I use this string:
https://api.binance.com/api/v3/account?timestamp=1499827319559&signature=here_I_put_my_secret_key
And I pass as a header as Danny suggested the apiKey.
But I get:
{
"code": -1021,
"msg": "Timestamp for this request is outside of the recvWindow."
}
Thanks.
I solved this correcting the time using javascript in Postman.
Another easy fix is to use the ccxt library : https://github.com/ccxt/ccxt
This might be what you're after, as per the documentation.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#endpoint-security-type
API-keys are passed into the Rest API via the X-MBX-APIKEY header.
In your Request, add that as the header key and your API Key as the value.
You can try this. This is working for me. Just Replace your API_KEY and SECRET
You need to retrieve serverTime time from https://api.binance.com/api/v3/time and need to use that serverTime to sign the request.
GET : https://api.binance.com/api/v3/account?timestamp={{timestamp}}&signature={{signature}}
Header:
Content-Type:application/json
X-MBX-APIKEY:YOUR_API_KEY
Pre-request Script :
pm.sendRequest('https://api.binance.com/api/v3/time', function (err, res) {
console.log('Timestamp Response: '+res.json().serverTime);
pm.expect(err).to.not.be.ok;
var timestamp = res.json().serverTime;
postman.setEnvironmentVariable('timestamp',timestamp)
postman.setGlobalVariable('timestamp',timestamp)
let paramsObject = {};
const binance_api_secret = 'YOUR_API_SECRET';
const parameters = pm.request.url.query;
parameters.map((param) => {
if (param.key != 'signature' &&
param.key != 'timestamp' &&
!is_empty(param.value) &&
!is_disabled(param.disabled)) {
paramsObject[param.key] = param.value;
}
})
Object.assign(paramsObject, {'timestamp': timestamp});
if (binance_api_secret) {
const queryString = Object.keys(paramsObject).map((key) => {
return `${encodeURIComponent(key)}=${paramsObject[key]}`;
}).join('&');
console.log(queryString);
const signature = CryptoJS.HmacSHA256(queryString, binance_api_secret).toString();
pm.environment.set("signature", signature);
}
function is_disabled(str) {
return str == true;
}
function is_empty(str) {
if (typeof str == 'undefined' ||
!str ||
str.length === 0 ||
str === "" ||
!/[^\s]/.test(str) ||
/^\s*$/.test(str) ||
str.replace(/\s/g,"") === "")
{
return true;
}
else
{
return false;
}
}
}
);
Get the official Postman collections for the Binance API from here:
https://github.com/binance/binance-api-postman
Import the desired collection and environment in Postman, for instance
binance_spot_api_v1.postman_collection.json
and binance_com_spot_api.postman_environment.json
Add your API key to the binance-api-key environment variable and your secret key to the binance-api-secret variable.
CAUTION: Limit what the key can do in Binance key management. Do not use this key for production, only for testing. Create new key for production.
For the signed requests calculate the signature in a Pre-request Script then set the signature environment variable.
Example Pre-request Script:
function resolveQueryString() {
const query = JSON.parse(JSON.stringify(pm.request.url.query))
const keyPairs = []
for (param of query) {
if (param.key === 'signature') continue
if (param.disabled) continue
if (param.value === null) continue
const value = param.value.includes('{{') ? pm.environment.get(param.key) : param.value
keyPairs.push(`${param.key}=${value}`)
}
return keyPairs.join('&')
}
const signature = CryptoJS.HmacSHA256(
resolveQueryString(),
pm.environment.get('binance-api-secret')
).toString(CryptoJS.enc.Hex)
pm.environment.set('signature', signature)

How to update credentials of specific folder in Jenkins using Groovy script?

I want to update a credentials object of an existing folder. How can I do that using groovy?
Here is what I have so far:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.hudson.plugins.folder.Folder
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
// Init
String user_name = "my_user_name"
String user_pass = "my_new_pass"
String folderName = "Projects"
Folder targetFolder = null
// Get folder:
def allJenkinsItems = Jenkins.getInstance().getItems();
for (currentJenkinsItem in allJenkinsItems)
{
if(!(currentJenkinsItem instanceof Folder)) {continue}
if(((Folder)currentJenkinsItem).getFullName().equals(folderName))
{
targetFolder = (Folder)currentJenkinsItem;
}
}
if (targetFolder == null) {println "Failed to find folder: folderName"; return}
// Get target credentials of that folder:
def credsList = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
targetFolder,
null,
null
);
// Get target creds out of the list - will get the first one it encounters:
def targetCreds = credsList.findResult { it.username == user_name ? it : null }
if (targetCreds == null) {println "Failed to find username: $user_name under credentials of folder: $folderName"; return}
// Gets store - how to get the folder's store??
def credentials_store = Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
// Try to update the creds of the folder.
// **updateResult is always 'false' here**
def updateResult = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
targetCreds,
new UsernamePasswordCredentialsImpl(targetCreds.scope, targetCreds.id, targetCreds.description, targetCreds.username, user_pass)
)
if (updateResult) {
println "Success changing password for ${user_name}"
} else {
println "Failed changing password for ${user_name}"
}
But when I am trying to update - I get a updateResult == false.
How can I update the credentials after they are found?
Found it myself:
/*
* Configures single (username & password) credentials for a folder in global domain
* if already exists a credentials with defined username - it will update it
* if more than one exists - the first one it encounters will be updated
*/
import java.util.logging.Logger
import jenkins.model.*
import com.cloudbees.hudson.plugins.folder.*;
import com.cloudbees.hudson.plugins.folder.properties.*;
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider.FolderCredentialsProperty;
import com.cloudbees.plugins.credentials.impl.*;
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.domains.*;
// Init
def logger = Logger.getLogger("")
jenkins = Jenkins.instance
String user_name = "my_user_name"
String user_pass = "my_new_pass"
String description = "my desc"
String folderName = "Projects"
String id = java.util.UUID.randomUUID().toString()
Credentials c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description: "+id, user_name, user_pass)
logger.info("Configuring domain credentials for folder: $folderName")
for (folder in jenkins.getAllItems(Folder.class)) {
if(folder.name.equals(folderName)) {
AbstractFolder<?> folderAbs = AbstractFolder.class.cast(folder)
FolderCredentialsProperty property = folderAbs.getProperties().get(FolderCredentialsProperty.class)
// If not defined FolderCredentialsProperty yet - define and finish
if(property == null) {
logger.info("Initializing folder credentials store and add credentials in global store")
property = new FolderCredentialsProperty([c])
folderAbs.addProperty(property)
jenkins.save()
return
}
// Check for existing credentials - and update their password & description
// will update the first credentials it encounters
def credentials_store = property.getStore()
List<com.cloudbees.plugins.credentials.Credentials> folderCredentialsList = property.getCredentials()
for (creds in folderCredentialsList) {
logger.info("Checking existing credentials of folder: $folderName for user: $user_name")
if (creds.username.equals(user_name)) {
// Found username - updating it
// Try to update the creds of the folder:
def updateResult = credentials_store.updateCredentials(
com.cloudbees.plugins.credentials.domains.Domain.global(),
creds,
new UsernamePasswordCredentialsImpl(creds.scope, creds.id, description, creds.username, user_pass)
)
if (updateResult) {
println "Update successful"
} else {
println "Update failed"
}
jenkins.save()
return
}
}
logger.info("Didn't find credntials with username: $user_name - adding new one")
// If got here - then:
// 1. There is already a FolderCredentials property defined for folder: folderName
// 2. didn't find any credentials(of username & password type) with username == user_name
// so just add the new credentials
property.getStore().addCredentials(Domain.global(), c)
jenkins.save()
return
}
}

How to map the Groovy script to Nexus script API and pass the Argument in JSON

I have a script which will add the nexus role to the LDAP user.
import org.sonatype.nexus.security.role.RoleIdentifier;
import org.sonatype.nexus.security.user.User;
import org.sonatype.nexus.security.user.UserManager;
String userId = 'NA12345';
String newRoleId = 'dot-maven'
String realm = 'LDAP'
String role_realm = 'default'
User user = security.securitySystem.getUser(userId, realm)
authManager = security.getSecuritySystem().getAuthorizationManager(UserManager.DEFAULT_SOURCE)
def existingRole = authManager.getRole(newRoleId)
if(user != null) {
RoleIdentifier newRole = new RoleIdentifier(role_realm, existingRole.roleId);
user.addRole(newRole)
security.securitySystem.setUsersRoles(user.getUserId(), realm, user.getRoles());
} else {
log.warn("No user with ID of $userId found.")
}
Now I need to add this script in the NExus Script API and pass the username and role id as argrument in JSON format.
How can i achieve this?

Grails access current environment from within config.groovy

Using the Grails OAuth plugin requires that an absolute callback URL be provided in Config.groovy. However I have different serverURLs for each environment.
Is there a way to get the current environment from inside Config.groovy, here's an example of what I want to do:
def devServerUrl = 'http://dev.example.com'
def prodServerUrl = 'http://prod.example.com'
def currentServerUrl = grailsApplication.metadata.environment == 'development' ? devServerUrl : prodServerUrl;
environments {
development {
grails {
serverURL = devServerUrl
}
}
production {
grails {
serverURL = prodServerUrl
}
}
}
oauth {
providers {
runkeeper {
api = RunKeeperApi
key = 'key'
secret = 'secret'
callback = currentServerUrl + '/oauth/runkeeper/callback'
}
}
}
Any ideas? Thanks!
Try this:
def currentServerUrl = Environment.current.name == 'development' ? devServerUrl : prodServerUrl;
I think it is cleaner to set different grails.serverURL for each environment and then do:
callback = "${grails.serverURL}/oauth/runkeeper/callback"

Logic block in Grails URLMappings

My site has urls like 'http://someRandomUsername.mysite.com'.
Sometimes users will try urls like
'http://www.someRandomeUsername.mysite.com'. I'd like to have some
logic in my url mappings to deal with this.
With the mappings below when I hit the page , with or without the
unneeded www, I get:
2012-03-01 14:52:16,014 [http-8080-5] ERROR [localhost].[/ambit] -
Unhandled exception occurred whilst decorating page
java.lang.IllegalArgumentException: URL mapping must either provide a
controller or view name to map to!
Any idea how to accomplish this? The mapping is below.
Thanks!
Jason
static mappings = {
name publicMap: "/$action?/$id?" {
def ret = UrlMappings.check(request)
controller = ret.controller
userName = ret.userName
}
}
static check =
{ request ->
def tokens = request?.serverName?.split(/\./) as List ?: []
def ret = [controller:'info']
if(tokens.size() > 3 && token[0] == 'www')
{
ret.userName = tokens[1]
ret.controller = 'redirect'
ret.action = 'removeWWW'
}
else if(tokens.size() == 3)
{
ret.userName = tokens[0]
ret.controller = 'info'
}
return ret
}
Honestly, like DmitryB said, the best way to do this is via the web server, whether it's IIS, Apache, or Tomcat.
Having said that, I feel the best way to accomplish this in Grails would be using filters.
You could create something like this in your ~/conf directory:
public class StripFilters {
def filters = {
stripWWWFilter(controller: '*', action: '*') {
before = {
def tokens = request.serverName.tokenize(/\./) ?: []
if(tokens.size() > 3 && tokens[0] == 'www') {
def url = request.request.requestURL.toString().replace('www.', '')
redirect([url:url, params: [userName: tokens[1]], permanent: true])
return false
}
}
}
}
}
This should do the trick.

Resources