Saturday, 23 September 2023

django print will causing http request not returning causing 500 error, use logging.info instead

 django 

print is bascially like echo, it will instruct the server to write output then browser treat as a response unable to be handleded (500)

return HttpResponse() wont exetue due to stderr basically like stdout behaviour


soluntion 

replace print with logger instead :


https://stackoverflow.com/questions/22134895/django-logging-to-console


In settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'app_api': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
    }

Somewhere in your application views

import logging
logger = logging.getLogger('app_api') #from LOGGING.loggers in settings.py

try:
    one = 1/0
except Exception as e:
    logger.error(e)

Friday, 22 September 2023

SSL certificate common name, SAN, subject

subject:

https://stackoverflow.com/questions/650017/what-does-subject-mean-in-certificate#:~:text=The%20subject%20of%20the%20certificate,owner%22%20of%20the%20certificate).

 

The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.

X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.

The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".


common name is part of subject


common name 

common name usually only matters in the subject, which is the name of the domain that cert is given to.

https://support.dnsimple.com/articles/what-is-common-name/#commonname-format


he Common Name (AKA CN) represents the server name protected by the SSL certificate. The certificate is valid only if the request hostname matches the certificate common name. Most web browsers display a warning message when connecting to an address that does not match the common name in the certificate.


The common name is not a URL. It doesn’t include any protocol (e.g. http:// or https://), port number, or pathname. For instance, https://example.com or example.com/path are incorrect. In both cases, the common name should be example.com.

It must precisely match the server name where the certificate is installed. If the certificate is issued for a subdomain, it should be the full subdomain. For instance, for the www and api subdomains of example.com, the common name will be www.example.com or api.example.com, and not example.com.



SAN 


Subject Alternative Name


a list of common name cert is protecting

he common name can only contain up to one entry: either a wildcard or non-wildcard name. It’s not possible to specify a list of names covered by an SSL certificate in the common name field.

The Subject Alternative Name extension (also called Subject Alternate Name or SAN) was introduced to solve this limitation. The SAN allows issuance of multi-name SSL certificates.

The ability to directly specify the content of a certificate SAN depends on the Certificate Authority and the specific product. Most certificate authorities have historically marketed multi-domain SSL certificates as a separate product. They’re generally charged at a higher rate than a standard single-name certificate.

On the technical side, the SAN extension was introduced to integrate the common name. Since HTTPS was first introduced in 2000 (and defined by the RFC 2818), the use of the commonName field has been considered deprecated, because it’s ambiguous and untyped.

The CA/Browser Forum has since mandated that the SAN would also include any value present in the common name, effectively making the SAN the only required reference for a certificate match with the server name. The notion of the common name survives mostly as a legacy of the past. There are active discussions to remove its use from most browsers and interfaces.

Thursday, 21 September 2023

Print pem file with in a single line string

 https://serverfault.com/questions/466683/can-an-ssl-certificate-be-on-a-single-line-in-a-file-no-line-breaks



1) print a single line string with \n for line breaks(this is needed because many software will not working properly with

awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}'  ca.pem
2) print a single line string without \n (SAML metadata etc)

awk 'NF {sub(/\r/, ""); printf "%s",$0;}' ca.pem

HTTP/SSL lets encrypt, or CA either uses private/public key pair from your own server or they generate for u, browser HTTPS validation

 browser https validation:


https://www.linkedin.com/pulse/how-does-your-browser-knows-tls-certificate-presented-ehis-iribhogbe



lets encrypt how it works:


https://letsencrypt.org/how-it-works/


The official Let’s Encrypt client can either use an already-created key pair, which you can generate under any circumstances you prefer, or it can perform the generation for you, which it will do with OpenSSL, see letsencrypt/crypto_util.py 184.


*Note: generation for you meaning that it will run script to generate public/private key pairs on your server.



def make_key(bits):

    """Generate PEM encoded RSA key.


    :param int bits: Number of bits, at least 1024.


    :returns: new RSA key in PEM form with specified number of bits

    :rtype: str


    """

    assert bits >= 1024  # XXX

    key = OpenSSL.crypto.PKey()

    key.generate_key(OpenSSL.crypto.TYPE_RSA, bits)

    return OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)


Thursday, 14 September 2023

servicenow - send email to create catalog request item(sc_req_item) and trigger workflow for both sc_request and sc_req_item and save sc_req_item customized variables

 https://www.servicenow.com/community/now-platform-forum/create-catalog-request-through-email-inbound-action/m-p/1138512


https://www.servicenow.com/community/developer-forum/create-catalog-request-item-through-inbound-email-action/m-p/1438688



1) Need to use email inboud action :

Inbound Action: Create Requested Item


Table: sc_req_item


Condition: <your condition here>



2) then use the following script :


(function runAction(/*GlideRecord*/ current, /*GlideRecord*/ event, /*EmailWrapper*/ email, /*ScopedEmailLogger*/ logger, /*EmailClassifier*/ classifier) {
createRequest();
function createRequest() {
       var grRequest = new GlideRecord ("sc_request");
       grRequest.initialize();
       grRequest.requested_for = sys_email.user_id;
       grRequest.short_description = email.subject.toString();
       grRequest.description = "received from: " + email.origemail + "\n\n" + email.body_text;
       var requestSysId = grRequest.insert();
       current.requested_for = '';
       current.short_description = email.subject.toString();
       current.description = "received from: " + email.origemail + "\n\n" + email.subject.toString() + "\n\n" + email.body_text;
       current.cat_item = 'SYS_ID OF THE CATALOG ITEM';
       current.parent = requestSysId;
       current.request = requestSysId;
       current.request_type = 'others';
       current.application= '';
       current.assignment_group='';
    var w = new Workflow();
       wfSysId = w.getWorkflowFromName("EXACT WORKFLOW NAME");
       w.startFlow(wfSysId, current, current.operation());
       current.insert();
}
})(current, event, email, logger, classifier);

3) sc_req_item customized variables

How to access service catalog item variable :

https://www.servicenow.com/community/itom-forum/where-catalog-variable-s-value-are-stored/m-p/908331



ar item = new GlideRecord("sc_req_item");



   item.addQuery("request", requestSys_id);



   item.query();



   if (item.next()) { 



// grab all variable sets from the parent request



     var var_own = new GlideRecord('sc_item_option_mtom');



     var_own.addQuery('request_item', item.sys_id);     



     //var_own.addQuery('sc_item_option.item_option_new.u_approval_display', 'global');



     var_own.orderBy('sc_item_option.item_option_new.order');



     var_own.query();       



     



     while (var_own.next()){



           



             gs.print(var_own.sc_item_option.item_option_new.question_text + ": " + eval('item.variable_pool.'+var_own.sc_item_option.item_option_new.name+'.getDisplayValue()') + "\n");



       }



       



     }

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


so to use code to save variables 

1) first insert question and value to sc_item_option, search by sc_item_option.list, insert question and value per row, and record sysId
2) then use sys_id from 1) and sys_id of your sc_req_item and insert into sc_item_option_mtom


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


Wednesday, 30 August 2023

serviceNow widgets - ag-grid

serviceNow :

widget -> dependency -> create new


new dependency -> JS includes -> https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.noStyle.js


new dependency -> CSS includes ->https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-grid.css

https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-theme-alpine.css

https://www.ag-grid.com/javascript-data-grid/getting-started/

serviceNow widgets with angular provider

 mainly used for reusing a directive/component over and over again in side of a component or other component, note templateUrl has to be bind to a widget so if you wana re-use the same angular provider for different widgets, maybe considering using tempalte strings.



widgets: angular provider :


https://www.youtube.com/watch?v=vnDklla7Vsc


https://www.google.com/search?sca_esv=559894069&rlz=1C1GCEA_enCA1031CA1031&sxsrf=AB5stBiCN4FCXOyBUHXvLt6hdaQf9aMrpA:1692925333942&q=servicenow+can+you+add+a+widget+in+service+catalog&tbm=vid&source=lnms&sa=X&ved=2ahUKEwi7naSpzvaAAxUqGDQIHYH1BeMQ0pQJegQIDhAB&biw=1920&bih=963&dpr=1#fpstate=ive&vld=cid:380b8a22,vid:xgWLAnHoPcA


https://serviceportal.io/creating-angular-directive-service-portal/


function(){

 return {

 link: function($scope){

 $scope.displayMessage = function() {

 alert('Hello World');

 };

 },

 restrict: 'A', // use 'A' for attribute or 'E' for element 

 replace: 'true',

 template: '<div ng-click="displayMessage()" class="btn btn-primary">This is a Directive</div>'

 };

}

To use your Angular Provider you will need to associate it with a widget by linking the two together using the “Angular Providers” related list on the widget form.


Now you can use the directive within any of the HTML of that widget. For example:



<div sp-button></div> <!-- for Attribute -->

 

<sp-button></sp-button> <!-- for Element -->



// replace entire <sp-button></sp-button> withe provided tempalteUrl

replace: true. 


templateUrl -> sp_ng_template.list


scope : {

// input all must be lower cases 

field : '=', (pass in object)

input2 : '@', (pass in text)

}



css formatted by global or outer


can use $rootscope as well to pass events 


    $rootScope.$on('test', function (event, data) {

        console.log(LOG_TAG, ' - event - ', event);

        console.log(LOG_TAG, ' - data - ', data);

    });

only problem is templateUrl is bind to widget, for useability, need to use string literals