Here is my code can anybody suggest me what to do also NOTE: My app only supports from android 6 to 10 devices only so suggest me accordingly
private fun shareInvoice(){
binding.consLayout1.isDrawingCacheEnabled = true
binding.consLayout1.buildDrawingCache()
binding.consLayout1.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH
val bitmap:Bitmap = binding.consLayout1.drawingCache
val sdf = SimpleDateFormat("dd-MM-yyyy hh:mm:ss", Locale.getDefault())
val root = Environment.getExternalStorageDirectory().absoluteFile
val file = File(root,"/Pictures")
val imageName = "ServiceInvoice_${businessName}_${sdf.format(System.currentTimeMillis())}"
val myFile = File(file,imageName)
if (myFile.exists()){
myFile.delete()
}
try {
val fos = FileOutputStream(myFile)
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fos)
fos.flush()
fos.close()
showMessage("Invoice generated successfully")
binding.consLayout1.isDrawingCacheEnabled = false
Log.e("INVOICE TAG", "shareInvoice:$myFile")
}catch (e:Exception){
Log.e("FOS TAG", "shareInvoice:$e")
}
}
Follow the method
private Uri saveImageExternal(Bitmap image) {
//TODO - Should be processed in another thread
Uri uri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "to-share.png");
FileOutputStream stream = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 90, stream);
stream.close();
uri = Uri.fromFile(file);
} catch (Execption e) {
Log.d(TAG, "IOException while trying to write file for sharing: " + e.getMessage());
}
return uri;
}
private void shareImageUri(Uri uri){
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/png");
startActivity(intent);
}
So Call
Uri uri = saveImageExternal(bitmap);
shareImageUri(uri);
Don't Forget to add in manifest and Request The Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/>
Here i get the final solution of my question if anybody wants to implement this functionality in their application
Thank you people those who posted their suggestion and interest.
This code i have tested in Android version 9,10,11 and 7
private fun scanFile(path: String) {
try {
MediaScannerConnection.scanFile(context, arrayOf(path), null) { path, uri ->
Log.d(
"Tag",
"Scan finished. You can view the image in the gallery now."
)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun shareInvoice(){
val file1 = File(
context?.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path,
Common.APP_DIRECTORY
)
if (!file1.exists()) {
file1.mkdirs()
}
val fileName = file1.absolutePath + "/" + System.currentTimeMillis() + ".jpg"
val bitmap = binding.sectionScreenShot.getBitmapFromView()
try {
val fos = FileOutputStream(File(fileName))
bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, fos)
fos.flush()
fos.close()
showMessage(getString(R.string.message_invoice_generated))
scanFile(fileName)
val uriForFile = FileProvider.getUriForFile(requireContext(),
requireContext().applicationContext.packageName + ".provider",
File(fileName))
val share `enter code here`= Intent(Intent.ACTION_SEND)
share.type = "image/jpg"
share.putExtra(Intent.EXTRA_STREAM, uriForFile)
lifecycleScope.launch {
delay(1000)
startActivity(Intent.createChooser(share, "Share Invoice"))
}
} catch (e: Exception) {
Log.e("FOS TAG", "shareInvoice:$e")
}
}
Hi I'm trying to convert a python code to C#. My Problem is, that I have a problem to make a HttpWebRequest. I don't get the cookies for the POST Request.
The Website response is 404. That is correct. But I think, I need the cookies for the POST request.
Is it correctly transleted? I have not done a HttpWebRequest yet.
C# Code:
public string email = "test#example.com"
public string password = "123456"
public string client_id = "111111111111"
public string login_url = "https://account.komoot.com/v1/signin"
var headers = new Dictionary<string, string> {
{"Content-Type", "application/json"}};
var payload = new Dictionary<string, string> {
{"email", email},
{"password", password},
{"reason", "null"}};
try
{
var request = (HttpWebRequest)WebRequest.Create(login_url);
request.CookieContainer = new CookieContainer();
var response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
var exeptionResponse = ex.Response;
var cookies = exeptionResponse ["Cookies"];
throw new WebException();
}
try
{
var request = (HttpWebRequest)WebRequest.Create(login_url);
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/json";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write(payload);
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
Console.WriteLine(result);
}
}
catch (Exception exe)
{
throw new Exception();
}
Python Code:
import requests
import json
email = "test#example.com"
password = "123456"
client_id = "111111111111"
login_url = "https://account.komoot.com/v1/signin"
tour_url = f"https://www.komoot.de/user/{client_id}/tours"
s = requests.Session()
res = requests.get(login_url)
cookies = res.cookies.get_dict()
headers = {
"Content-Type": "application/json"
}
payload = json.dumps({
"email": email,
"password": password,
"reason": "null"
})
s.post(login_url,
headers=headers,
data=payload,
cookies=cookies,
)
url = "https://account.komoot.com/actions/transfer?type=signin"
s.get(url)
headers = {"onlyprops": "true"}
response = s.get(tour_url, headers=headers)
if response.status_code != 200:
print("Something went wrong...")
exit(1)
data = response.json()
tours = data["user"]["_embedded"]["tours"]["_embedded"]["items"]
for idx in range(len(tours)):
print(f"({idx+1}) {tours[idx]['name']}")
tour_nr = int(input("Tour ID: "))
tour_nr -= 1
tour_url = tours[tour_nr]["_links"]["coordinates"]["href"]
response = s.get(tour_url, headers=headers)
tour_data = json.loads(response.text)
tour = tours[tour_nr]
tour['coordinates'] = tour_data
print("Title:", T.name())
print(f"Duration: {T.duration()}s")
Tanks for your help!
Try it
public async Task<string> HttpClientAsync(string json, string token)
{
try
{
var JsonData = new StringContent(json, Encoding.UTF8, "application/json");
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
using (var client = new HttpClient(handler))
{
// System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var result = await client.PostAsync(url, JsonData);
string resultContent = await result.Content.ReadAsStringAsync();
return resultContent;
}
}
catch (Exception e)
{
return e.Message;
}
}
I am trying to convert this Python code to C# (.NET Core ideally).
Source
My goal is to convert the QR input string to another string containing the data in json. See the provided links.
#! /usr/bin/env python3
import json
import sys
import zlib
import base45
import cbor2
from cose.messages import CoseMessage
payload = sys.argv[1][4:]
print("decoding payload: "+ payload)
# decode Base45 (remove HC1: prefix)
decoded = base45.b45decode(payload)
# decompress using zlib
decompressed = zlib.decompress(decoded)
# decode COSE message (no signature verification done)
cose = CoseMessage.decode(decompressed)
# decode the CBOR encoded payload and print as json
print(json.dumps(cbor2.loads(cose.payload), indent=2))
I couldn't find any NuGet package for Zlib, that would work correctly. So I am stuck straight after base45 decoding. Thanks for any tips.
using System.Text; //Rystem.Text.Base45 NuGet
var removedHeader = testQrData.Substring(4);
var decoded = removedHeader.FromBase45();
byte[] rawBytes = Encoding.ASCII.GetBytes(decoded);
This link might be helpful for further investigation.
Decoding scheme
IBarcodeReader reader = new BarcodeReader();//using Zxing
var barcodeBitmap = (Bitmap)Bitmap.FromFile("qrcode.png");
var barcodeReader = new BarcodeReader();
var qrcontent = barcodeReader.Decode(barcodeBitmap).Text;
var qrmessage = qrcontent.Substring(4);//remove first 4 chars
byte[] decodedBase45 = Base45Encoding.Decode(qrmessage);//using base45 lib
var cose = ZlibStream.UncompressBuffer(decodedBase45);//using zlib or similar
var decrypted = Message.DecodeFromBytes(cose).GetContent(); //using COSE
CBORObject cbor = CBORObject.DecodeFromBytes(decrypted); //using Peter.O.. CBOR
var jsonDecoded = cbor.ToJSONString(); //or deserialize it to custom class
I added "Zlib.Portable" from NuGet and used "ZlibStream.UncompressString"
byte[] decoded = Base45Encoding.Decode(input);
var stringResult = ZlibStream.UncompressString(decoded);`
I'm stuck in the next step "CoseMessage.decode" :/
I have used the ZXing library in the past to decode and create QR Codes:
https://github.com/micjahn/ZXing.Net
You could also try: https://github.com/codebude/QRCoder
A quick ZXing example from their github page:
// create a barcode reader instance
IBarcodeReader reader = new BarcodeReader();
// load a bitmap
var barcodeBitmap = (Bitmap)Image.LoadFrom("C:\\sample-barcode-image.png");
// detect and decode the barcode inside the bitmap
var result = reader.Decode(barcodeBitmap);
// do something with the result
if (result != null)
{
txtDecoderType.Text = result.BarcodeFormat.ToString();
txtDecoderContent.Text = result.Text;
}
This example reads a QR Code image.
I'm not sure what your input is but i would assume it's also an image in binary format so you might have to play around to get it working.
This solution works for me.
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
using System.IO;
using Com.AugustCellars.COSE;
using PeterO.Cbor;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Collections.Generic;
namespace DGCVerification.Services {
public class DGCVerificationService: IDGCVerificationService {
private readonly string _certificatePrefix = "HC1:";
private readonly ILogger < DGCVerificationService > _logger;
public DGCVerificationService(ILogger < DGCVerificationService > logger) {
_logger = logger;
}
private bool TryTrimPrefix(string certificateString, out string result) {
if (!certificateString.StartsWith(_certificatePrefix)) {
result = null;
return false;
}
result = certificateString.Substring(_certificatePrefix.Length);
return true;
}
private byte[] DecompressFromZlib(byte[] input) {
using(var memoryStream = new MemoryStream(input)) {
using(var decompressionStream = new InflaterInputStream(memoryStream)) {
using(var resultStream = new MemoryStream()) {
decompressionStream.CopyTo(resultStream);
var result = resultStream.ToArray();
return result;
}
}
}
}
private bool VerifyCoseSignature(Sign1Message coseMessage, string signature) {
var signatureAsBytes = Convert.FromBase64String(signature);
var publicKey = OneKey.FromX509(signatureAsBytes);
var result = coseMessage.Validate(publicKey);
_logger.LogInformation($"cose message signature {signature} verified as {result}");
return result;
}
private DGCPayload DecodeAndDeserialize(string certificateString, out Sign1Message coseMessage) {
coseMessage = null;
if (!TryTrimPrefix(certificateString, out
var trimmedPrefixString)) {
_logger.LogInformation($"certificate {certificateString} didn't have proper prefix {_certificatePrefix}");
return null;
}
var bytesBase256 = Base45Encoding.Decode(trimmedPrefixString);
_logger.LogInformation($"certificate {certificateString} base45 decoded to {Convert.ToBase64String(bytesBase256)}");
var decompressedFromZlib = DecompressFromZlib(bytesBase256);
_logger.LogDebug($"certificate {certificateString} zlib decompressed to {Convert.ToBase64String(decompressedFromZlib)}");
coseMessage = Message.DecodeFromBytes(decompressedFromZlib) as Sign1Message;
var coseMessagePayload = coseMessage.GetContent();
var cborResult = CBORObject.DecodeFromBytes(coseMessagePayload);
var jsonResult = cborResult.ToJSONString();
var result = JsonConvert.DeserializeObject < DGCPayloadCzechVersionRoot > (jsonResult);
return result.DGCPayloadWrap.DGCPayload;
}
private bool IsNotExpiredDGC(DGCPayload dGCPayload, UzisData uzisData) {
var vaccine = dGCPayload.Vaccination?.FirstOrDefault();
if (vaccine != null) {
var vaccinationValidityRules = uzisData.DGCValidityCzechRules.Rules
.FirstOrDefault()
.PlatnostiVakcinace;
var rule = vaccinationValidityRules.FirstOrDefault(x => x.VaccineMedicinalProduct == vaccine.Mp) ??
vaccinationValidityRules.FirstOrDefault(x => x.VaccineMedicinalProduct == null);
if (!DateTime.TryParse(vaccine.Dt, out
var vaccinatedOnDate)) {
_logger.LogError($"couldn't parse date of vaccination for DGC : {JsonConvert.SerializeObject(dGCPayload)}");
return false;
}
var result = DateTime.Now.Date <= vaccinatedOnDate.AddMonths(rule.OdolnostMesicDo);
return result;
}
var test = dGCPayload.Test?.FirstOrDefault();
if (test != null) {
var testValidityRule = uzisData.DGCValidityCzechRules.Rules
.FirstOrDefault()
.PlatnostiTestu
.FirstOrDefault(x => x.TypeOfTest == test.Tt);
if (!DateTime.TryParse(test.Tr, out
var testedOnDate)) {
_logger.LogError($"couldn't parse date of test for DGC : {JsonConvert.SerializeObject(dGCPayload)}");
return false;
}
var result = DateTime.Now.Date <= testedOnDate.AddHours(testValidityRule.PlatnostHod);
return result;
}
var recovery = dGCPayload.Recovery?.FirstOrDefault();
if (recovery != null) {
if (!DateTime.TryParse(recovery.Du, out
var recoveryValidUntil)) {
_logger.LogError($"couldn't parse recovert valid until for DGC : {JsonConvert.SerializeObject(dGCPayload)}");
return false;
}
var result = DateTime.Now.Date <= recoveryValidUntil;
return result;
}
return false;
}
private string GetCountryFromDGC(DGCPayload dGCPayload) {
var result = dGCPayload.Vaccination?.FirstOrDefault()?.Co ??
dGCPayload.Test?.FirstOrDefault()?.Co ??
dGCPayload.Recovery?.FirstOrDefault()?.Co;
if (result == null) {
throw new ArgumentException($"couldn't retrieve country from DGC. dgc : {JsonConvert.SerializeObject(dGCPayload)}");
}
return result;
}
private List < SignatureCertificate > GetFittingSignatures(DGCPayload dGCPayload, UzisData uzisData) {
try {
var country = GetCountryFromDGC(dGCPayload);
var result = uzisData.NationalCertificateSignatures.SignatureCertificate
.Where(x => x.Active)
.Where(x => x.Country == country)
.Where(x => x.CertificateType == "DSC")
.ToList();
return result;
} catch (Exception e) {
_logger.LogError(e, $"Filtering signatures from UZIS failed with exception");
return null;
}
}
private bool IsProperlySignedDGC(string certificateString, DGCPayload dGCPayload, Sign1Message coseMessage, UzisData uzisData) {
var fittingSignatures = GetFittingSignatures(dGCPayload, uzisData);
var result = false;
foreach(var signature in fittingSignatures) {
try {
var signatureVerificationResult = VerifyCoseSignature(coseMessage, signature.RawData);
_logger.LogInformation($"certificate {certificateString} signature validation against signature {signature} resulted in {signatureVerificationResult}");
result |= signatureVerificationResult;
} catch (Exception e) {
_logger.LogError(e, $"certificate {certificateString} signature validation against signature {signature} failed with exception");
}
}
return result;
}
public bool IsValidDgc(string certificateString, UzisData uzisData, out DGCPayload decodedDGCPayload, out VerificationResult verificationResult) {
decodedDGCPayload = null;
Sign1Message coseMessage = null;
try {
decodedDGCPayload = DecodeAndDeserialize(certificateString, out coseMessage);
if (coseMessage == null) {
_logger.LogInformation($"certificate {certificateString} decoded to null COSE");
verificationResult = VerificationResult.UnableToDecode;
return false;
}
} catch (Exception e) {
_logger.LogError(e, $"certificate {certificateString} decoding failed with exception");
verificationResult = VerificationResult.UnableToDecode;
return false;
}
var isProperlySigned = IsProperlySignedDGC(certificateString, decodedDGCPayload, coseMessage, uzisData);
if (!isProperlySigned) {
verificationResult = VerificationResult.InvalidSignature;
return false;
}
var isNotExpired = IsNotExpiredDGC(decodedDGCPayload, uzisData);
if (!isNotExpired) {
verificationResult = VerificationResult.Expired;
return false;
}
verificationResult = VerificationResult.Valid;
return true;
}
}
}
And the tricky base45
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DGCVerification
{
public class Base45Encoding
{
private static readonly Dictionary<byte, char> _encodingTable = new Dictionary<byte, char>
{
{0x0,'0'},
{0x1,'1'},
{0x2,'2'},
{0x3,'3'},
{0x4,'4'},
{0x5,'5'},
{0x6,'6'},
{0x7,'7'},
{0x8,'8'},
{0x9,'9'},
{0xA,'A'},
{0xB,'B'},
{0xC,'C'},
{0xD,'D'},
{0xE,'E'},
{0xF,'F'},
{0x10,'G'},
{0x11,'H'},
{0x12,'I'},
{0x13,'J'},
{0x14,'K'},
{0x15,'L'},
{0x16,'M'},
{0x17,'N'},
{0x18,'O'},
{0x19,'P'},
{0x1A,'Q'},
{0x1B,'R'},
{0x1C,'S'},
{0x1D,'T'},
{0x1E,'U'},
{0x1F,'V'},
{0x20,'W'},
{0x21,'X'},
{0x22,'Y'},
{0x23,'Z'},
{0x24,' '},
{0x25,'$'},
{0x26,'%'},
{0x27,'*'},
{0x28,'+'},
{0x29,'-'},
{0x2A,'.'},
{0x2B,'/'},
{0x2C,':'},
};
private static readonly Dictionary<char, byte> _decodingTable;
static Base45Encoding()
{
_decodingTable = _encodingTable.ToDictionary(x => x.Value, x => x.Key);
}
private static List<byte> ToBytesBase45(string charsBase45)
{
var result = new List<byte>(charsBase45.Length);
foreach (var character in charsBase45)
{
if (!_decodingTable.TryGetValue(character, out byte asByte))
{
throw new FormatException($"input string contains {character} with numeric value {char.GetNumericValue(character)} on index {charsBase45.IndexOf(character)} which is not valid base45 character");
}
result.Add(asByte);
}
return result;
}
private static List<ushort> ToShortsBase10(List<byte> bytesBase45)
{
var result = new List<ushort>(bytesBase45.Count);
ushort num = 0;
double pow = 0;
for (int i = 0; i != bytesBase45.Count; ++i, ++pow)
{
num += (ushort)(bytesBase45[i] * Math.Pow(45, pow));
if (pow == 2 || i == (bytesBase45.Count -1))
{
result.Add(num);
num = 0;
pow = -1;
}
}
return result;
}
private static List<byte> ToBytesBase256(List<ushort> shortsBase10, int charBase45Length)
{
var result = new List<byte>(shortsBase10.Count);
for (int i = 0; i != shortsBase10.Count; ++i)
{
var num = (byte)(shortsBase10[i] / 256);
if(!(i == (shortsBase10.Count - 1)
&& charBase45Length % 3 != 0
&& num == 0))
{
result.Add(num);
}
result.Add((byte)(shortsBase10[i] % 256));
}
return result;
}
public static byte[] Decode(string charsBase45)
{
if (charsBase45.Length % 3 == 1)
{
throw new FormatException("input string does not have correct length. mod 3 == 1. it isnt base45");
}
var bytesBase45 = ToBytesBase45(charsBase45);
var shortsBase10 = ToShortsBase10(bytesBase45);
var bytesBase256 = ToBytesBase256(shortsBase10, charsBase45.Length);
return bytesBase256.ToArray();
}
}
}
Decode/encode base45:
/// <summary>
/// https://tools.ietf.org/html/draft-faltstrom-baseBaseSize-01
/// TL/DR:
/// This encoding takes a byte array, splits it into 2 byte chunks and encodes each chunk as 3 characters.
/// Any remaining byte is encoded as 2 characters, padded with a '0' when the remaining byte has value < 45.
/// </summary>
public static class Base45Encoding
{
private const int BaseSize = 45;
private const int BaseSizeSquared = 2025;
private const int ChunkSize = 2;
private const int EncodedChunkSize = 3;
private const int SmallEncodedChunkSize = 2;
private const int ByteSize = 256;
private static readonly char[] _Encoding = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*',
'+', '-', '.', '/', ':' };
private static readonly Dictionary<char, byte> _Decoding = new(BaseSize);
static Base45Encoding()
{
for(byte i = 0; i < _Encoding.Length; ++i)
_Decoding.Add(_Encoding[i], i);
}
public static string Encode(byte[] buffer)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
var wholeChunkCount = buffer.Length / ChunkSize;
var result = new char[wholeChunkCount * EncodedChunkSize + (buffer.Length % ChunkSize == 1 ? SmallEncodedChunkSize : 0)];
if (result.Length == 0)
return string.Empty;
var resultIndex = 0;
var wholeChunkLength = wholeChunkCount * ChunkSize;
for (var i = 0; i < wholeChunkLength;)
{
var value = buffer[i++] * ByteSize + buffer[i++];
result[resultIndex++] = _Encoding[value % BaseSize];
result[resultIndex++] = _Encoding[value / BaseSize % BaseSize];
result[resultIndex++] = _Encoding[value / BaseSizeSquared % BaseSize];
}
if (buffer.Length % ChunkSize == 0)
return new string(result);
result[^2] = _Encoding[buffer[^1] % BaseSize];
result[^1] = buffer[^1] < BaseSize ? _Encoding[0] : _Encoding[buffer[^1] / BaseSize % BaseSize];
return new string(result);
}
public static byte[] Decode(string value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length == 0)
return Array.Empty<byte>();
var remainderSize = value.Length % EncodedChunkSize;
if (remainderSize == 1)
throw new FormatException("Incorrect length.");
var buffer = new byte[value.Length];
for (var i = 0; i < value.Length; ++i)
{
if (_Decoding.TryGetValue(value[i], out var decoded))
{
buffer[i] = decoded;
continue; //Earliest return on expected path.
}
throw new FormatException($"Invalid character at position {i}.");
}
var wholeChunkCount = buffer.Length / EncodedChunkSize;
var result = new byte[wholeChunkCount * ChunkSize + (remainderSize == ChunkSize ? 1 : 0)];
var resultIndex = 0;
var wholeChunkLength = wholeChunkCount * EncodedChunkSize;
for (var i = 0; i < wholeChunkLength; )
{
var val = buffer[i++] + BaseSize * buffer[i++] + BaseSizeSquared * buffer[i++];
result[resultIndex++] = (byte)(val / ByteSize); //result is always in the range 0-255 - % ByteSize omitted.
result[resultIndex++] = (byte)(val % ByteSize);
}
if (remainderSize == 0)
return result;
result[^1] = (byte)(buffer[^2] + BaseSize * buffer[^1]); //result is always in the range 0-255 - % ByteSize omitted.
return result;
}
}
Cannot to sign in, i run localy in docker my container, i can sign-in on my machine and docker no error, but on my remote server i cannot to login, it doesn't write cookie in reponse, have no error, just don't write response. It just redirect me on my page which i setted,and after that i got error, cause i have no my cookie authorization key inside cookie.
video
My SignIn method
#auth_router.post('/signin')
async def sign_in(response: Response, username: str = Form(...), password: str = Form(...), recaptchav3: str = Form(...)) -> dict:
is_human = await verify_recaptcha(recaptchav3)
if is_human['success']:
user = await authenticate_user(username, password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid username or password',
)
user_obj = await User_Pydantic.from_tortoise_orm(user)
user_token = await generate_token(user_obj)
response.set_cookie(key="Authorization", value=user_token, httponly=True, secure=True, expires=(8*60*60))
response.headers["Authorization"] = user_token
user.jwt_token = user_token
await user.save()
return {
'access_token': user_token,
'token_type': 'bearer'
}
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid captcha',
)
How i submit my form js
const request = (method, url, data = null, redirectPage) => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(method, url, true)
// xhr.setRequestHeader('Content-Type', 'multipart/form-data')
xhr.onerror = function (event) {
alert(event)
console.log(event);
};
xhr.onload = () => {
if (xhr.status === 200) {
return window.location.href = redirectPage;
return resolve(JSON.parse(xhr.responseText || '{}'))
} else {
alert(`Request failed with status ${xhr.status}`)
reject(new Error(`Request failed with status ${xhr.status}`))
return window.location.reload();
}
}
if (data) {
if (typeof data === 'string' || data instanceof String || typeof data.constructor == Object){
xhr.send(JSON.stringify(data))
} else {
xhr.send(data)
}
} else {
xhr.send()
}
})
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData, 'dashboard');
} else{
alert('Перезагрузите страницу');
}
}
})
I cannot understand why using the built-in method in fastapi it does not write on the remote server, it worked on the local one, but I solved the problem by writing. token via js.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie(cookieValue) {
var user = getCookie("Authorization");
if (user == "") {
if (cookieValue != "" && cookieValue != null) {
setCookie("Authorization", cookieValue, 365);
}
}
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData);//, 'dashboard');
isLogened.then(result => {
checkCookie(result.access_token);
return window.location.href = 'dashboard';
}, result => {
log('Cant get response')
});
} else{
alert('Перезагрузите страницу');
}
}
})
I have a Swift app that loads a timestamp and a number as a json file and sends it as with POST through Alamofire.
var newPostStamp = ["title": "\(stamp)", "body": string1]
Alamofire.request(.POST, "mywebsite.com/post", parameters: newPostStamp, encoding: .JSON)
.responseJSON { (request, response, data, error)}...
Can you tell me how I can handle the arguments in from the POST request in my server? I am using this tutorial (http://joelinoff.com/blog/?p=1658) but I don't know how to change the do_POST() method to handle my request. I just need it to show me a new page with all the timestamp:values that I have sent so far.
Thanks!
This worked for me.
// Add this to your class
import SystemConfiguration
import CoreData
func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress){
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
func connectionService(jsonString:NSDictionary) -> NSDictionary
{
var request = NSMutableURLRequest(URL: NSURL(string: "https://example.com")!)
var response: NSURLResponse?
var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &error)
request.timeoutInterval = 100
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")
//Reconnnection 5 times
for (var i = 0; i < 5 ; i++)
{
let date1 = NSDate();
var formatter = NSDateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
let defaultTimeZoneStr1 = formatter.stringFromDate(date1);
var error: NSError?
println("Connecting to server : \(defaultTimeZoneStr1)")
if isConnectedToNetwork (){
let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
if error != nil || urlData!.length == 0
{
println("Error happend timeout======\(error?.code)!")
continue
}
else
{
let date = NSDate();
var formatter = NSDateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
let defaultTimeZoneStr = formatter.stringFromDate(date);
println("Response from server : \(defaultTimeZoneStr)")
if let httpResponse = response as? NSHTTPURLResponse
{
println("Status Code for successful------------------------------------>\(httpResponse.statusCode)")
if (httpResponse.statusCode == 502)
{
// Server is down
break
}
else
{
println(NSString(data: urlData!, encoding: NSUTF8StringEncoding)!)
var er: NSError?
let JSONresdata: AnyObject = (NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers,error: &er)!)
println("JSON response : \(JSONresdata)")
JSONdata = JSONresdata as! NSDictionary
}
}
}
}
else
{
println("------------------------------------------------No network----------------------------------------------")
// You can add your code
break
}
}
return JSONdata as! NSDictionary;
}
Hope this might be helpful.