Giter VIP home page Giter VIP logo

postcard_creator_wrapper's Introduction

Postcard Creator

PyPI version codecov PyPI version License

A python wrapper around the Rest API of the Swiss Postcard creator.

Installation

# requires python 3.6 or later
$ pip install postcard-creator

Setup / API Usage

from postcard_creator.postcard_creator import PostcardCreator

w = PostcardCreator(token)
w.get_quota()
w.get_user_info()
w.get_billing_saldo()
w.has_free_postcard()
w.send_free_card(postcard=)

Usage

Log in with your SwissID credentials. Note that 2-factor authentication is not supported (See #40 (comment)).

from postcard_creator.postcard_creator import PostcardCreator, Postcard, Token, Recipient, Sender

token = Token()
token.fetch_token(username='', password='')
token.has_valid_credentials(username='', password='')
recipient = Recipient(prename='', lastname='', street='', place='', zip_code=0000)
sender = Sender(prename='', lastname='', street='', place='', zip_code=0000)
card = Postcard(message='', recipient=recipient, sender=sender, picture_stream=open('./my-photo.jpg', 'rb'))

w = PostcardCreator(token)
w.send_free_card(postcard=card, mock_send=False, image_export=False)

Advanced configuration

The following keyword arguments are available for advanced configuration.

PostcardCreator#send_free_card():

  • image_export=False: Export postcard image to current directory (os.getcwd)
  • mock_send=False: Do not submit order (testing)
  • fallback_color_fill=False: On False: If image is too small, force upscale to match postcard aspect ration (background-size: contain), on True: fallback to color fill mode where image is centered and border is filled with most dominant color found in image.

Logging

import logging

logger = logging.getLogger('postcard_creator')

# log levels
# 5: trace
# 10: debug
# 20: info
# 30: warning

Example

Test

pip install -r requirements.txt
pip install -r requirements-dev.txt
pip install -e .
pytest

Related

Release notes

2.4, 2023-08-12

  • add fallback_color_fill parameter in send_free_card()

v2.3, 2022-09-30

  • changes in internals of swissid token authentication due to introduction of anomaly-detection #41

v2.2, 2021-07-07

  • drop support for postcard_creator_legacy
  • update legacy (username/ password) token authentication due to changed endpoints
    • note: legacy method now uses postcard_creator_swissid endpoints instead of postcard_creator_legacy, postcard_creator_legacy is out of life

v2.1, 2021-05-16

  • update requests to v2.25.1 to fix "AttributeError: 'NoneType' object has no attribute 'group'" in authentication. #27

v2.0, 2021-02

  • support of new swissid authentication (access_token with code/ code_verifier)
  • support of new endpoints at https://pccweb.api.post.ch/secure/api/mobile/v1
  • class PostcardCreator is a proxy which instantiates an endpoint wrapper compatible with authentication method of token, underlying wrappers are: PostcardCreatorSwissId, PostcardCreatorLegacy
  • migration to v2.0
    • with authentication method swissid: if you rely on get_billing_saldo(), get_user_info(): these endpoints return data in different format
    • customizations image_target_width, image_target_height, image_quality_factor no longer compatible with authentication method swissid
  • require python 3.6 or later

v1.1, 2020-01-30

  • support for swissid authentication
  • Method Token#has_valid_credentials and Token#fetch_token introduce a parameter method which can be set to one of these vals: ['mixed', 'legacy', 'swissid']. 'mixed' is default and tries both authentication procedures

v0.0.8, 2018-03-28

  • Migrate to postcardcreator API 2.2

v0.0.7, 2017-12-28

  • Fix issues with PNG images #6

v0.0.6, 2017-11-22

  • internal changes
  • do not use requirements.txt in setup.py anymore. set all requirements in install_requires without explicit version numbers

Troubleshooting

“The headers or library files could not be found for jpeg”

pip install fails with the above error. Install libjpeg as discussed here https://stackoverflow.com/questions/44043906/the-headers-or-library-files-could-not-be-found-for-jpeg-installing-pillow-on

"AttributeError: 'FreeTypeFont' object has no attribute 'getsize'"

pip install Pillow==9.5.0

Author

Andrin Bertschi
https://twitter.com/andrinbertschi

License

Apache License 2.0

<3

postcard_creator_wrapper's People

Contributors

abertschi avatar emazzotta avatar maede97 avatar matbech avatar nheiniger avatar wp99cp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

postcard_creator_wrapper's Issues

Valid Credicals

if i run this code on the new wrapper:

from postcard_creator.postcard_creator import PostcardCreator, Postcard, Token, Recipient, Sender
import datetime

email = '[email protected]'
pw = '********'
token = Token()
token.fetch_token(username=email, password=pw,method='legacy')
token.has_valid_credentials(username=email, password=pw,method='legacy')

w = PostcardCreator(token)
print(w.has_free_postcard())

it throws this error:

ERROR:root:Username/password authentication failed. Are your credentials valid?.
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/postcard_creator/token.py", line 120, in fetch_token
    raise PostcardCreatorException()
postcard_creator.postcard_creator.PostcardCreatorException

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "status.py", line 12, in <module>
    token.fetch_token(username=email, password=pw,method='legacy')
  File "/usr/local/lib/python3.7/dist-packages/postcard_creator/token.py", line 133, in fetch_token
    raise e
postcard_creator.postcard_creator.PostcardCreatorException: Could not get access_token. Something broke. set increase debug verbosity to debug why

bevore version v1.1 it worked well with this code. Now I added the method='legacy' parameter to the token.fetch_token and token.has_valid_credentials as it is documented.

Any help?

implement fill_mode

currently, pictures are resized to fill the specified area and cropped as needed (cover). Implement a fill_mode to change this behaviour:

fill_mode:

  • cover: default
  • contain: resize the image so that it can fit in the specified area without crop
  • text_aware: if picture contains text at the borders, choose fill_mode contain, otherwise cover. This prevents pictures with messages to be cropped.

Endpoint issues with SwissID login

postcard_creator_wrapper currently malfunctioning.

postcards_folder (INFO): checking for valid accounts
22095root (INFO): using legacy username password authentication
22096root (INFO): legacy username password authentication failed
22097root (ERROR): Username/password authentication failed. Are your credentials valid?.
22098root (INFO): using swissid username password authentication
22099Traceback (most recent call last):
22100  File "/home/bean/projects/postcards/venv/bin/postcards-folder", line 11, in <module>
22101    load_entry_point('postcards', 'console_scripts', 'postcards-folder')()
22102  File "/home/bean/projects/postcards/postcards.git/postcards/plugin_folder/postcards_folder.py", line 134\
     , in main
22103    PostcardsFolder().main(sys.argv[1:])
22104  File "/home/bean/projects/postcards/postcards.git/postcards/postcards.py", line 52, in main
22105    self.do_command_send(args)
22106  File "/home/bean/projects/postcards/postcards.git/postcards/postcards.py", line 102, in do_command_send
22107    stop_on_first_valid=not args.all_accounts)
22108  File "/home/bean/projects/postcards/postcards.git/postcards/postcards.py", line 175, in _create_pcc_wrap\
     pers
22109    if token.has_valid_credentials(account.get('username'), account.get('password')):
22110  File "/home/bean/projects/postcards/venv/lib/python3.6/site-packages/postcard_creator/token.py", line 72\
     , in has_valid_credentials
22111    self.fetch_token(username, password, method=method)
22112  File "/home/bean/projects/postcards/venv/lib/python3.6/site-packages/postcard_creator/token.py", line 10\
     4, in fetch_token
22113    saml_response = self._get_swissid_saml_response(session, username, password)
22114  File "/home/bean/projects/postcards/venv/lib/python3.6/site-packages/postcard_creator/token.py", line 19\
     9, in _get_swissid_saml_response
22115    goto_param = re.search(r'&goto=(.*?)$', step1_goto_url.url).group(1)
22116AttributeError: 'NoneType' object has no attribute 'group'

postcard_creator.postcard_creator.PostcardCreatorException: fail to fetch https://account.post.ch/idp/

I have just followed the example to send a postcard, however I get a response of

postcard_creator.postcard_creator.PostcardCreatorException: fail to fetch https://account.post.ch/idp/?login&targetURL=https://pccweb.api.post.ch/SAML/ServiceProvider/?redirect_uri=ch.post.pcc://auth/XXXXXXXXXXXXXXXXXXX&profile=default&app=pccwebapi&inMobileApp=true&layoutType=standard

Any help would be great,
Best regards,

authentication not working

It looks like authentication is not working for me. I use swissid and I checked on post.ch and the app that my login is correct.

My code

from postcard_creator.postcard_creator import (
    Token,
)

token = Token()
token.fetch_token(username="myemail", password="mypw", method="swissid")

The Error

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    token.fetch_token(username="myemail", password="mypw", method="swissid")
  File "/home/r/python/postcard/.venv/lib/python3.8/site-packages/postcard_creator/token.py", line 128, in fetch_token
    raise e
  File "/home/r/python/postcard/.venv/lib/python3.8/site-packages/postcard_creator/token.py", line 122, in fetch_token
    access_token = self._get_access_token_swissid(session, username, password)
  File "/home/r/python/postcard/.venv/lib/python3.8/site-packages/postcard_creator/token.py", line 340, in _get_access_token_swissid
    url = step7_soup.find('form', {'name': 'LoginForm'})['action']
TypeError: 'NoneType' object is not subscriptable

Did post change the API?
BTW I found this project because I wanted to do the exact same. Good job!

Reference to pytest-runner in setup.py

pip install postcard-creator

Collecting postcard-creator
  Using cached https://files.pythonhosted.org/packages/b7/fa/d7261b4be791bbb9930492372b9d8b78896adb9048778da2f93a5b9ff51f/postcard_creator-2.1.tar.gz
    Complete output from command python setup.py egg_info:
    Couldn't find index page for 'pytest-runner' (maybe misspelled?)
    No local packages or working download links found for pytest-runner
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-88znyog3/postcard-creator/setup.py", line 38, in <module>
        test_suite = 'tests',
      File "/home/bean/.pyenv/versions/3.6.1/lib/python3.6/distutils/core.py", line 108, in setup
        _setup_distribution = dist = klass(attrs)
      File "/home/bean/projects/postcards/source/venv/lib/python3.6/site-packages/setuptools/dist.py", line 315, in __init__
        self.fetch_build_eggs(attrs['setup_requires'])
      File "/home/bean/projects/postcards/source/venv/lib/python3.6/site-packages/setuptools/dist.py", line 361, in fetch_build_eggs
        replace_conflicting=True,
      File "/home/bean/projects/postcards/source/venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 850, in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "/home/bean/projects/postcards/source/venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1122, in best_match
        return self.obtain(req, installer)
      File "/home/bean/projects/postcards/source/venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1134, in obtain
        return installer(requirement)
      File "/home/bean/projects/postcards/source/venv/lib/python3.6/site-packages/setuptools/dist.py", line 429, in fetch_build_egg
        return cmd.easy_install(req)
      File "/home/bean/projects/postcards/source/venv/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 659, in easy_install
        raise DistutilsError(msg)
    distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('pytest-runner')

Workaround until new version released:

pip install pytest-runner

then try again:
pip install postcard-creator

Same applies for pip package: postcards

Token authentication with 'legacy' method no longer works

I tought this was temporary but I can reproduce it now everytime

steps to reproduce

  • [X ] OS: Win10 (fresh install, latest updates)
  • with latest Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
  • same behavior on Linux...
  • Network: swisscom and UPC ( so I thought initially it was related to the provider - it is not)
  • username password work with the official postcardcreator app (not linked to a swissid, normal account, tried as well other account which work with the official app)
  • it works with a swissid account, but not with a standard username / password Swiss Post Customer Login

started python

Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
from postcard_creator.postcard_creator import PostcardCreator, Postcard, Token, Recipient, Sender
token = Token()
token.fetch_token(username='myusername',password='mypassword')

results in

Traceback (most recent call last):
File "c:\temp\venv\lib\site-packages\postcard_creator\token.py", line 276, in _get_access_token_swissid
url = resp.json()['nextAction']['successUrl']
KeyError: 'nextAction'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "c:\temp\venv\lib\site-packages\postcard_creator\token.py", line 129, in fetch_token
raise e
File "c:\temp\venv\lib\site-packages\postcard_creator\token.py", line 123, in fetch_token
access_token = self._get_access_token_swissid(session, username, password)
File "c:\temp\venv\lib\site-packages\postcard_creator\token.py", line 279, in _get_access_token_swissid
raise PostcardCreatorException("failed to login, username/password wrong?")
postcard_creator.postcard_creator.PostcardCreatorException: failed to login, username/password wrong?

any ideas?

Swissid login failed

I have the following error:

Traceback (most recent call last):
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/bin/postcards-folder", line 8, in <module>
    sys.exit(main())
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcards/plugin_folder/postcards_folder.py", line 134, in main
    PostcardsFolder().main(sys.argv[1:])
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcards/postcards.py", line 55, in main
    self.do_command_send(args)
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcards/postcards.py", line 104, in do_command_send
    wrappers, try_again_after = self._create_pcc_wrappers(accounts,
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcards/postcards.py", line 178, in _create_pcc_wrappers
    if token.has_valid_credentials(account.get('username'), account.get('password')):
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcard_creator/token.py", line 84, in has_valid_credentials
    self.fetch_token(username, password, method=method)
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcard_creator/token.py", line 129, in fetch_token
    raise e
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcard_creator/token.py", line 123, in fetch_token
    access_token = self._get_access_token_swissid(session, username, password)
  File "/Users/stevegenoud/.virtualenvs/postcards-oUvzP0s_/lib/python3.9/site-packages/postcard_creator/token.py", line 357, in _get_access_token_swissid
    url = step7_soup.find('form', {'name': 'LoginForm'})['action']
TypeError: 'NoneType' object is not subscriptable

I guess that they changed their login page and it broke the login flow you implemented.

P.S. Thanks for the great tool, I use it for a small project for a friend's wedding. People uploaded photos of the wedding day and I send them as a postcard twice a week!

Features to implement

  • write tests

    • use the Responses lib to mock requests calls
  • accept a stream instead of a location to read post card image

  • add option to temporarily cache token on disk

Unexpected `.postcard_creator_wrapper_sent` folder

Hi 👋 I noticed that the postcards-folder script always creates a .postcard_creator_wrapper_sent folder, which I guess is only used for debugging. I think the issue is in create_text_cover, where the image_export is hard-coded to True.

def create_text_cover(self, msg):
"""
Create a jpg with given text
"""
return create_text_image(msg, image_export=True)

Renew expired token causes an error

Why does the following code always give an error message? In other words, how is it possible to refresh an expired token?

import time
from postcard_creator.postcard_creator import Token

token = Token()
token.fetch_token(username='...', password='...', method='swissid')
print(token.headers)

time.sleep(token.token_expires_in)  # wait until token expires

token = Token()  # the program also crashes, if you leave out this line of code
token.fetch_token(username='...', password='...', method='swissid')
print(token.headers)

I think the problem is caused by the following request. The second time we post our credentials we got a 403 as a response. And the problem must be in the postcard_creator_wrapper code since if you just rerun the entire program the authentication succeeds.

url = "https://login.swissid.ch/api-login/authenticate/basic?locale=en&goto=" + goto_param + \
"&acr_values=loa-1&realm=%2Fsesam&service=qoa1"
headers = request_headers
headers['authId'] = auth_id
step_data = {
'username': username,
'password': password
}
resp = session.post(url, json=step_data, headers=headers, allow_redirects=True)
_log_and_dump(resp)

Instead of creating a new token object every time, it would be nice to have a method refetch_token, that clears the local vars, e.g., success and fetches a new token. Usecase: First, you check when the next postcard can be sent. Then the program waits until a timer expires, refreshes the access token and send the postcard.

SwissID login is now failing because of anomaly detection

It seems that a new step has been introduced in the login flow of SwissID. After the login with username and password, the authentication isn't immediately successful but requires an additional step. Currently the wrapper doesn't implement this step and thus, fails to authenticate.

In the code, this happens here:

url = resp.json()['nextAction']['successUrl']
where the successUrl is not found in the response. Instead, a trace shows the following:

postcard_creator (TRACE):
< POST /api-login/authenticate/basic?locale=en&goto=https%3A%2F%2Flogin.swissid.ch%3A443%2Fidp%2Foauth2%2Fauthorize%3Fscope%3Dopenid%2520email%2520phone%2520profile%26response_type%3Dcode%26redirect_uri%3Dhttps%253A%252F%252Faccount.post.ch%252Fredirect%252Fid-confirmation%26state%3DKecrj74wbqBVMfBEwxWv6-7VpsInqwWLcgIgeCkZyCU%26nonce%3D5C5MpAKvPpj3DteI-OmG2PsNrd30kBzvwpVs0twH-bo%26client_id%3Dklp-client%26ui_locales%3Den%26acr_values%3Dloa-1%26prompt%3D%26acr%3Dloa-1%26acr_sig%3DYeLkH7STHI11H3jx57IwMB8Xmb77iil1_IWccGf--Kg&acr_values=loa-1&realm=%2Fsesam&service=qoa1 HTTP/1.1
< Host: login.swissid.ch
< User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
< Accept-Encoding: gzip, deflate
< Accept: */*
< Connection: keep-alive
< authId: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3aGl0ZWxpc3Qtc3RhdGUiOiIzMjg1MTkzNC00NmU5LTQ3MDEtODIzMi02ODA3NjA3ZjBiMGQiLCJhdXRoSW5kZXhWYWx1ZSI6InFvYTEiLCJvdGsiOiJkbzA4dTVlbmZtMmI5b3AzcmMyYW03N3NvaiIsImF1dGhJbmRleFR5cGUiOiJzZXJ2aWNlIiwicmVhbG0iOiIvc2VzYW0iLCJzZXNzaW9uSWQiOiJxWWRtQWFiVnZ6eDVad2ViQk9YVkFERzZ3V1kuKkFBSlRTUUFDTURFQUFsTkxBQnhHUzJ4RFMydHdiblJEVVZaNWMxUlFWMVp3VjBGbVMyUkxSV2M5QUFSMGVYQmxBQWhEVkZOZlFWVlVTQUFDVXpFQUFBLi4qIiwiZXhwIjoxNjY0NTMxNTI4LCJpYXQiOjE2NjQ1MzA4MDh9.U77KIkQNUlw3rU2SfeQ_ei4dVAQfiHMEgE3BynOGWqw
< Content-Length: 66
< Content-Type: application/json
<
< {"username": [CUT] "password": "[CUT]"}
> HTTP/1.1 200
> Content-Type: application/json
> Transfer-Encoding: chunked
> Connection: keep-alive
> X-Correlation-ID: 2f0-IjtO-Wdy4
> Vary: Origin
> Vary: Access-Control-Request-Method
> Vary: Access-Control-Request-Headers
> Date: Fri, 30 Sep 2022 09:40:08 GMT
> X-Xss-Protection: 1; mode=block
> Referrer-Policy: strict-origin-when-cross-origin
> X-Content-Type-Options: nosniff
> X-Frame-Options: DENY
> Permissions-Policy: interest-cohort=()
> Set-Cookie: swissid=expired; Path=/; Domain=swissid.ch; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Strict; HttpOnly
> Set-Cookie: swissid=expired; Path=/; Domain=login.swissid.ch; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Strict; HttpOnly
> Strict-Transport-Security: max-age=31536000; includeSubDomains
>
{"status":"NOT_AUTHENTICATED","tokens":{"authId":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3aGl0ZWxpc3Qtc3RhdGUiOiIxNTY5ODBmYS1jYWZmLTRkMDgtOTU0NC05YzVhNjFhNTVhNGYiLCJhdXRoSW5kZXhWYWx1ZSI6InFvYTEiLCJvdGsiOiJyNjFkN2E1NWI1dmwwNmlrN3Z0NnFqNmp1dCIsImF1dGhJbmRleFR5cGUiOiJzZXJ2aWNlIiwicmVhbG0iOiIvc2VzYW0iLCJzZXNzaW9uSWQiOiJxWWRtQWFiVnZ6eDVad2ViQk9YVkFERzZ3V1kuKkFBSlRTUUFDTURFQUFsTkxBQnhHUzJ4RFMydHdiblJEVVZaNWMxUlFWMVp3VjBGbVMyUkxSV2M5QUFSMGVYQmxBQWhEVkZOZlFWVlVTQUFDVXpFQUFBLi4qIiwiZXhwIjoxNjY0NTMxNTI4LCJpYXQiOjE2NjQ1MzA4MDh9.acGv5KZHMFYcBvuGYlpLD2z-o_NYpwVHjb_gFpXLTWM"},"nextAction":{"type":"SEND_DEVICE_PRINT"},"switchOptions":[]}

When looking in a browser for this part of the logging flow, the next step is a new request as follows:

POST /api-login/anomaly-detection/device-print?service=qoa1&locale=de&goto=https:%2F%2Flogin.swissid.ch%2Fidp%2Foauth2%2Fauthorize%3Fscope%3Dopenid%2Bemail%2Bphone%2Bprofile%26response_type%3Dcode%26redirect_uri%3Dhttps%253A%252F%252Faccount.post.ch%252Fredirect%252Fid-confirmation%26state%3Dnc5cVQRBuV-MlBHVyUTd9jdvtjML4JsdEihOUQNAkhQ%26nonce%3DQsNkhPvZ1LwNlQc1hPMjWg9fbqqwIqZqwUKGr1SsyPw%26client_id%3Dklp-client%26ui_locales%3Dde%26acr_values%3Dloa-1%26prompt%3D%26acr%3Dloa-1%26acr_sig%3Dbj0A7ftVEoh-4-ongxPymEDWi-Ripn_Y2W4j8_x-P5I&acr_values=loa-1&realm=%2Fsesam HTTP/1.1
Host: login.swissid.ch
Cookie: firstTimeLogin=true; lang=de
Content-Length: 937
Sec-Ch-Ua: "Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"
Accept: application/json, text/plain, */*
Content-Type: application/json
Authid: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3aGl0ZWxpc3Qtc3RhdGUiOiIzODk5MGMxNS1jMzRiLTRiMmUtYjBiZC05NTIxNTY4NGZmMGQiLCJhdXRoSW5kZXhWYWx1ZSI6InFvYTEiLCJvdGsiOiJibWFuM2JraHZxaXJkNHM2azZxNjJib2s2YSIsImF1dGhJbmRleFR5cGUiOiJzZXJ2aWNlIiwicmVhbG0iOiIvc2VzYW0iLCJzZXNzaW9uSWQiOiJEcW9LTVg2SDUyZUNKRVFyTk5HVmRXc2x5LVEuKkFBSlRTUUFDTURFQUFsTkxBQngzWmxwTFlUSkdPVE5DY1ZaMFdIRXlTakl6WkRNd1kzSjJTbmM5QUFSMGVYQmxBQWhEVkZOZlFWVlVTQUFDVXpFQUFBLi4qIiwiZXhwIjoxNjY0NTI5MDc5LCJpYXQiOjE2NjQ1MjgzNTl9.PbMn1KdGHD2Zef4WPyT9zUR-TIaXLTpvm5ZQQIuOQpE
Sec-Ch-Ua-Mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
Sec-Ch-Ua-Platform: "Windows"
Origin: https://login.swissid.ch
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: https://login.swissid.ch/login/fingerprint
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,fr;q=0.8
Connection: close

{"screen":{"screenWidth":1920,"screenHeight":1200,"screenColourDepth":24},"timezone":{"timezone":-120},"plugins":{"installedPlugins":"internal-pdf-viewer;internal-pdf-viewer;internal-pdf-viewer;internal-pdf-viewer;internal-pdf-viewer"},"fonts":{"installedFonts":"cursive;monospace;serif;sans-serif;fantasy;default;Arial;Arial Black;Arial Narrow;Bookman Old Style;Bradley Hand ITC;Century;Century Gothic;Comic Sans MS;Courier;Courier New;Georgia;Impact;Lucida Console;Monotype Corsiva;Papyrus;Tahoma;Times;Times New Roman;Trebuchet MS;Verdana"},"userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36","appName":"Netscape","appCodeName":"Mozilla","appVersion":"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36","platform":"Win32","product":"Gecko","productSub":"20030107","vendor":"Google Inc.","language":"en-US"}

And the response to this request finally contains the successUrl parameter:

HTTP/1.1 200 
Content-Type: application/json
Connection: keep-alive
X-Correlation-ID: 6eG-i8x8-zFL2
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Date: Fri, 30 Sep 2022 08:59:44 GMT
X-Xss-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Permissions-Policy: interest-cohort=()
Set-Cookie: swissid=X4RnGty_Je4wOY17LsB7ftxpBjY.*AAJTSQACMDEAAlNLABw0bUw0YTJkY24wczRBY1hHT21lOVN2ZjVEdWc9AAR0eXBlAANDVFMAAlMxAAA.*; Path=/; Domain=swissid.ch; Secure; HttpOnly; SameSite=Strict; HttpOnly
Set-Cookie: swissid=X4RnGty_Je4wOY17LsB7ftxpBjY.*AAJTSQACMDEAAlNLABw0bUw0YTJkY24wczRBY1hHT21lOVN2ZjVEdWc9AAR0eXBlAANDVFMAAlMxAAA.*; Path=/; Domain=login.swissid.ch; Secure; HttpOnly; SameSite=Strict; HttpOnly
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Length: 491

{"status":"AUTHENTICATED","nextAction":{"type":"REDIRECT_TO_RP","successUrl":"https://login.swissid.ch/idp/oauth2/authorize?scope=openid+email+phone+profile&response_type=code&redirect_uri=https%3A%2F%2Faccount.post.ch%2Fredirect%2Fid-confirmation&state=nc5cVQRBuV-MlBHVyUTd9jdvtjML4JsdEihOUQNAkhQ&nonce=QsNkhPvZ1LwNlQc1hPMjWg9fbqqwIqZqwUKGr1SsyPw&client_id=klp-client&ui_locales=de&acr_values=loa-1&prompt=&acr=loa-1&acr_sig=bj0A7ftVEoh-4-ongxPymEDWi-Ripn_Y2W4j8_x-P5I"},"switchOptions":[]}

I've tried to simply add this new request to the login flow but couldn't get it to work. I suspect, because of the endpoint name anomaly-detection/device-print, that this is made on purpose to avoid a programmatic login... but this is only speculation. I'd be happy to see if this can still be automated.

Is this wrapper still functional?

I was able to authenticate once, never again. Tried different Python versions, all within the specs. Not sure, any one using this wrapper successfully atm?

400 Error

Hello abertschi

I was really surprised that this fantastic API exists when I found it. I immediately had thousands of ideas about what to do with it. Unfourtenetley I got this annoying error every time I try it. (postcard_creator.postcard_creator.PostcardCreatorException: error in request put https://postcardcreator.post.ch/rest/2.2/users/503438/mailings/45985710/pages/2. status_code: 400)
Is this a known issue or am I doing something wrong?

Thanks for your reply.

Endpoint Issue with swissid authentication

postcard_creator (INFO): swissid username password authentication failed
postcard_creator (INFO): 'NoneType' object has no attribute 'group'
Traceback (most recent call last):
  File "/home/bean/projects/postcards/venv/bin/postcards-pexels", line 11, in <module>
    load_entry_point('postcards', 'console_scripts', 'postcards-pexels')()
  File "/home/bean/projects/postcards/postcards.git/postcards/plugin_pexels/postcards_pexels.py", line 24, in main
    PostcardsPexel().main(sys.argv[1:])
  File "/home/bean/projects/postcards/postcards.git/postcards/postcards.py", line 55, in main
    self.do_command_send(args)
  File "/home/bean/projects/postcards/postcards.git/postcards/postcards.py", line 105, in do_command_send
    stop_on_first_valid=not args.all_accounts)
  File "/home/bean/projects/postcards/postcards.git/postcards/postcards.py", line 178, in _create_pcc_wrappers
    if token.has_valid_credentials(account.get('username'), account.get('password')):
  File "/home/bean/projects/postcards/venv/lib/python3.6/site-packages/postcard_creator/token.py", line 84, in has_valid_credentials
    self.fetch_token(username, password, method=method)
  File "/home/bean/projects/postcards/venv/lib/python3.6/site-packages/postcard_creator/token.py", line 129, in fetch_token
    raise e
  File "/home/bean/projects/postcards/venv/lib/python3.6/site-packages/postcard_creator/token.py", line 123, in fetch_token
    access_token = self._get_access_token_swissid(session, username, password)
  File "/home/bean/projects/postcards/venv/lib/python3.6/site-packages/postcard_creator/token.py", line 236, in _get_access_token_swissid
    goto_param = re.search(r'goto=(.*?)$', step1_goto_url.url).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

Autentication with multiple connectet Accounts

There is a case that isn't covered with the new swissid Login.
On one SwissID login, you can have multiple Post-Accounts. In this case, the authenication fails and it says that the credicals arent valid.
If you login on the Postcard Creator App with the SwissID, after the login, it ask for the account on wich you want to choose.

Compatibility with python 3.6

we make use of module 'secrets' attribute 'token_bytes', does not seem to be available in python 3.6. this breaks compatibility with python 3.6. Investigate issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.